在 MSSQLServerManagementStudio 中处理事务的最佳方式

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

在 ManagementStudio (或任何其他查询工具)中,如何测试 SQL 语句,如果注意到它们破坏了什么,则回滚(在单独的查询中?)

182273 次浏览

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

比如说,

Begin Transaction


-Do some T-SQL queries here.


Rollback transaction -- OR commit transaction

如果要合并错误处理,可以使用 TRY... CATCH 块来实现。如果出现错误,您可以回滚 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

希望这有帮助,但请让我知道,如果你需要更多的细节。

我想添加一个点,您也可以(如果您正在编写的内容比较复杂,也应该这样做)添加一个测试变量来回滚(如果您处于测试模式)。然后你就可以立刻执行整个计划了。通常,我还会添加代码来查看各种操作的前后结果,特别是当它是一个复杂的脚本时。

例如:

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