TSQL Try / Catch within Transaction or vice versa?

后端 未结 3 1682
梦如初夏
梦如初夏 2020-11-30 04:06

I\'m writing a script that will delete records from a number of tables, but before it deletes it must return a count for a user to confirm before committing.

This is

3条回答
  •  旧巷少年郎
    2020-11-30 04:45

    In addition to the good advice by M.Ali and dean above, a little bit help for those looking to use the new(er) TRY CATCH THROW paradigm in SQL SERVER:

    (I couldn't easily find the complete syntax, so adding it here)

    GIST : HERE

    Sample stored procedure code here (from my gist):

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
     
    CREATE PROC [dbo].[pr_ins_test]
    @CompanyID INT
    AS
     
    SET NOCOUNT ON
     
    BEGIN
     
        DECLARE @PreviousConfigID INT
        
        BEGIN TRY
            BEGIN TRANSACTION MYTRAN; -- Give the transaction a name
            SELECT 1/0  -- Generates divide by zero error causing control to jump into catch
     
            PRINT '>> COMMITING'
            COMMIT TRANSACTION MYTRAN;
        END TRY
        BEGIN CATCH
            IF @@TRANCOUNT > 0
            BEGIN 
                PRINT '>> ROLLING BACK'
                ROLLBACK TRANSACTION MYTRAN; -- The semi-colon is required (at least in SQL 2012)
                
                
            END; -- I had to put a semicolon to avoid error near THROW
            THROW
        END CATCH
    END
    

提交回复
热议问题