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