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

后端 未结 2 1480
难免孤独
难免孤独 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:54

    I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.

    Example below:

    USE AdventureWorks;
    GO
    DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
    BEGIN TRANSACTION;
    
    BEGIN TRY
         IF @TEST= 1
            BEGIN
                SELECT *FROM Production.Product
                    WHERE ProductID = 980;
            END    
        -- Generate a constraint violation error.
        DELETE FROM Production.Product
        WHERE ProductID = 980;
    
         IF @TEST= 1
            BEGIN
                SELECT *FROM Production.Product
                    WHERE ProductID = 980;
                IF @@TRANCOUNT > 0
                    ROLLBACK TRANSACTION;
            END    
    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 AND @TEST = 0
        COMMIT TRANSACTION;
    GO
    

提交回复
热议问题