Add column to table and then update it inside transaction

后端 未结 6 1788
北荒
北荒 2020-12-08 12:33

I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall

6条回答
  •  执笔经年
    2020-12-08 13:22

    I almost agree with Remus but you can do this with SET XACT_ABORT ON and XACT_STATE

    Basically

    • SET XACT_ABORT ON will abort each batch on error and ROLLBACK
    • Each batch is separated by GO
    • Execution jumps to the next batch on error
    • Use XACT_STATE() will test if the transaction is still valid

    Tools like Red Gate SQL Compare use this technique

    Something like:

    SET XACT_ABORT ON
    GO
    BEGIN TRANSACTION
    GO
    
    IF COLUMNPROPERTY(OBJECT_ID('Color'), 'CodeID', ColumnId) IS NULL
       ALTER TABLE Color ADD CodeID [uniqueidentifier] NULL
    GO
    
    IF XACT_STATE() = 1
      UPDATE Color
      SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
      WHERE [Name] = 'Red'
    GO
    
    IF XACT_STATE() = 1
     COMMIT TRAN
    --else would be rolled back
    

    I've also removed the default. No value = NULL for GUID values. It's meant to be unique: don't try and set every row to all zeros because it will end in tears...

提交回复
热议问题