Pie*_*arg 17 sql-server t-sql transaction rollback
我有一些ALTER TABLE
我正在运行的声明。并非所有这些都有效(它们是运行 SQL 数据比较的结果),我想将它们分组到一些事务中,并在出现问题时回滚语句。
这可能吗,还是只能回滚数据?
Pet*_*ter 10
BEGIN TRANSACTION
BEGIN TRY
ALTER TABLE1...
ALTER TABLE2...
-- Additional data/structural changes
COMMIT
END TRY
BEGIN CATCH
ROLLBACK;
THROW; -- Only if you want reraise an exception (to determine the reason of the exception)
END CATCH
Run Code Online (Sandbox Code Playgroud)
小智 7
是的,可以ALTER TABLE
在一个事务中使用ROLLBACK
和使用多个语句COMMIT
。
这是您的脚本的脚手架(遵循MS 指南进行改进):
BEGIN TRANSACTION
BEGIN TRY
-- place your script in this TRY block
-- your DDL instructions:
ALTER TABLE1...
ALTER TABLE2...
-- data modifications:
EXEC('
UPDATE A
SET c1 = 23,
c2 = ''ZZXX'';
');
-- another DDL instruction:
ALTER TABLE2...
-- end of your script
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
-- If you want reraise an exception (to determine the reason of the exception)
-- just uncomment block with appropriate version:
-- SQL SERVER >= 2012
/*
THROW;
*/
-- SQL SERVER < 2012 (tested against 2008 R2)
/*
DECLARE @ErrorMessage VARCHAR(MAX);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (
@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
*/
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
Run Code Online (Sandbox Code Playgroud)
请注意,THROW
仅适用于 SQL SERVER 版本 >= 2012。在这里您可以将版本从semver转换为年份表示法:http : //sqlserverbuilds.blogspot.ru(不知道.ru
域,有英文版本)