在MS SQL Server Management Studio中处理事务的最佳方法


127

假设我有一个语法和语义上正确的SQL语句,因此它可以执行。

在Management Studio(或任何其他查询工具)中,如何测试SQL语句,如果我发现它们损坏了某些内容,请回滚(在单独的查询中?)。

Answers:


227

最简便的方法是将代码包装在事务中,然后逐行执行每批T-SQL代码。

例如,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

如果要合并错误处理,可以使用TRY ... CATCH BLOCK。如果发生错误,则可以回滚catch块中的事务。

例如:

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

有关更多详细信息,请参见以下链接。

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

希望对您有所帮助,但是如果您需要更多详细信息,请告诉我。


3
你好谢谢。我第一次在这里看到@@ TRANCOUNT,您能告诉我经过ROLLBACK处理后“ IF @@ TRANCOUNT> 0 COMMIT TRANSACTION”会发生什么情况吗?@@ TRANCOUNT有什么值?再次感谢。
QMaster

2
执行完ROLLBACK TRANSACTION之后,@@ TRANCOUNT会重新设置为0。这样,将不会执行COMMIT TRANSACTION。参见msdn.microsoft.com/de-de/library/ms187967.aspx
ChristophBrückmann'16年

8

我想添加一点,如果您处于测试模式,则还可以(并且如果编写的内容很复杂)也可以将测试变量添加到回滚。然后,您可以立即执行整个操作。通常,我还会添加代码以查看各种操作的前后结果,特别是如果它是一个复杂的脚本。

下面的例子:

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.