Best way to work with transactions in MS SQL Server Management Studio

后端 未结 2 1448
难免孤独
难免孤独 2020-12-07 07:08

Let\'s say I have an SQL statement that\'s syntactically and semantically correct so it executes.

In Management Studio (or any other query tool) how can I test SQL

2条回答
  •  离开以前
    2020-12-07 07:55

    The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

    For example,

    Begin Transaction
    
             -Do some T-SQL queries here.
    
    Rollback transaction -- OR commit transaction
    

    If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

    For example:

    USE AdventureWorks;
    GO
    BEGIN TRANSACTION;
    
    BEGIN TRY
        -- Generate a constraint violation error.
        DELETE FROM Production.Product
        WHERE ProductID = 980;
    END TRY
    BEGIN CATCH
        SELECT 
            ERROR_NUMBER() AS ErrorNumber
            ,ERROR_SEVERITY() AS ErrorSeverity
            ,ERROR_STATE() AS ErrorState
            ,ERROR_PROCEDURE() AS ErrorProcedure
            ,ERROR_LINE() AS ErrorLine
            ,ERROR_MESSAGE() AS ErrorMessage;
    
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
    END CATCH;
    
    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;
    GO
    

    See the following link for more details.

    http://msdn.microsoft.com/en-us/library/ms175976.aspx

    Hope this helps but please let me know if you need more details.

提交回复
热议问题