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
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
请注意,THROW仅适用于 SQL SERVER 版本 >= 2012。在这里您可以将版本从semver转换为年份表示法:http ://sqlserverbuilds.blogspot.ru (不知道.ru域,有英文版)
是的,这是可能的。
大多数 DDL 语句可以在 SQL Server 中回滚(有一些例外,例如
CREATE DATABASE
)是的,可以
ALTER TABLE
在一个事务中使用ROLLBACK
和的多个语句COMMIT
。这是您的脚本的脚手架(遵循MS 指南并进行了改进):
请注意,
THROW
仅适用于 SQL SERVER 版本 >= 2012。在这里您可以将版本从semver转换为年份表示法:http ://sqlserverbuilds.blogspot.ru (不知道.ru
域,有英文版)您需要研究 T-SQL 中的事务和异常处理。查看此页面上的最后两个示例:http: //msdn.microsoft.com/en-us/library/ms175976.aspx