假设我有一个SQL语句,它在语法和语义上都是正确的,因此它会执行.
在Management Studio(或任何其他查询工具)中,我如何测试SQL语句,如果我注意到它们破坏了某些内容,则回滚(在单独的查询中?)
最简单的方法是将代码包装在事务中,然后逐行执行每批T-SQL代码.
例如,
Begin Transaction -Do some T-SQL queries here. Rollback transaction -- OR commit transaction
如果要包含错误处理,可以使用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
希望这有帮助,但如果您需要更多详细信息,请告诉我.
我想添加一点,如果您处于测试模式,则还可以(并且如果编写的内容很复杂)也可以将测试变量添加到回滚。然后,您可以立即执行整个操作。通常,我还会添加代码以查看各种操作的前后结果,特别是如果它是一个复杂的脚本。
下面的例子:
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