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

比方说,我有一个SQL语句在语法和语义上是正确的,所以它执行。

在Management Studio(或任何其他查询工具)中,如何testingSQL语句,如果我注意到他们打破了某些内容,则回滚(在单独的查询中)?

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

例如,

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

如果你想joinerror handling,你可以通过使用TRY … CATCH BLOCK来实现。 如果发生错误,则可以在catch块中回滚tranasction。

例如:

 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

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

我想添加一点,你也可以(也应该如果你写的是复杂的)添加一个testingvariables回滚,如果你在testing模式。 那么你可以一次执行整个事情。 通常我也添加代码来查看各种操作的前后结果,特别是如果它是一个复杂的脚本。

示例如下:

 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