SQL Server 2000 - ALTER TABLE + INSERT INTO = Errors?

后端 未结 2 776
盖世英雄少女心
盖世英雄少女心 2021-01-07 22:11

I\'m trying to alter a table to add a new column, then insert a new row into it.

ALTER TABLE Roles ADD ModifiedDate DateTime;
INSERT INTO Roles (Name, [Descr         


        
相关标签:
2条回答
  • 2021-01-07 22:49

    What about transations?

    BEGIN TRANSACTION;
    ALTER TABLE Roles ADD ModifiedDate DateTime;
    GO;
    COMMIT TRANSACTION;
    
    BEGIN TRANSACTION;
    INSERT INTO Roles (Name, [Description], CreatedBy, BuiltIn, Created, ModifiedDate) VALUES ('Name', 'Description', 0, 1, GETDATE(), GETDATE());
    GO;
    COMMIT TRANSACTION;
    
    0 讨论(0)
  • 2021-01-07 23:07

    As expected. SQL Server does not execute line by line. It compiles and parse the batch, and when this happens the column does not exist.

    You need to decouple the 2 actions thus

    ALTER TABLE Roles ADD ModifiedDate DateTime;
    EXEC ('
        INSERT INTO Roles (Name, [Description], CreatedBy, BuiltIn, Created, ModifiedDate)
        VALUES (''Name'', ''Description'', 0, 1, GETDATE(), GETDATE())
    ')
    

    A "GO" is a batch separator only for client tools and is not recognised by the server

    0 讨论(0)
提交回复
热议问题