Sql server /代码>的选项。以下脚本在通过SSM运行时生成两个错误: begin transaction go set xact_abort on go create table T(ID int not null,constraint CK_ID check (ID=4)) go insert into T(ID) values (3) go rollback

Sql server /代码>的选项。以下脚本在通过SSM运行时生成两个错误: begin transaction go set xact_abort on go create table T(ID int not null,constraint CK_ID check (ID=4)) go insert into T(ID) values (3) go rollback,sql-server,transactions,Sql Server,Transactions,错误: Msg 547, Level 16, State 0, Line 7 The INSERT statement conflicted with the CHECK constraint "CK_ID". The conflict occurred in database "TestDB", table "dbo.T", column 'ID'. Msg 3903, Level 16, State 1, Line 9 The ROLLBACK TRANSACTION request has

错误:

Msg 547, Level 16, State 0, Line 7
The INSERT statement conflicted with the CHECK constraint "CK_ID". The conflict occurred in database "TestDB", table "dbo.T", column 'ID'.
Msg 3903, Level 16, State 1, Line 9
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
但是,相同的脚本保存为Abortable.sql,并使用以下命令行运行:

sqlcmd -b -E -i Abortable.sql -S .\SQL2014 -d TestDB
生成单个错误:

Msg 547, Level 16, State 1, Server .\SQL2014, Line 1
The INSERT statement conflicted with the CHECK constraint "CK_ID". The conflict
occurred in database "TestDB", table "dbo.T", column 'ID'.

因此,看起来从命令行运行脚本并使用
-b
选项可能是另一种方法。我刚刚搜索了SSMS选项/属性,看看是否可以找到与
-b
等价的东西,但我没有找到它。

根据我的说明,链接帖子断言命名的事务应该绕过这一点。你认为这准确吗?如果是,请详细说明原因?此外,无法删除
GO
。。。该脚本需要
GO
s才能编译。如果我删除了
GO
s,那么依赖于新添加/重命名列的后续语句将无法编译。将整个内容放在try/catch块中,并在catch中回滚。@SeanLange-
try
/
catch
也不允许跨批,因此如果需要
GO
s,这行不通。@Damien_The_unsiver-天哪,我甚至没有注意到它是多批次的……这将教会我在周一早上喝完第一杯咖啡之前发表评论。你也需要在catch中回滚事务,否则你会有一个事务保持打开状态。这就是他想要的,不是吗?它是用于测试脚本的?是的,但如果出现错误,它将下降到您的捕获中,并且需要在那里回滚,否则事务将被孤立。据我所知,它是孤立的,以便可以在该状态下测试结果。是的,这种方法已经奏效。这就像罪恶一样丑陋,但如果没有更好的办法,这似乎是最好的办法。原则上,这个问题将保留几天时间。如果我不回来接受这个答案,请随意纠缠。@Brondahl-我刚刚做了一个实质性的补充-看起来还有另一种方法不需要对脚本进行重大更改,如果您愿意使用
sqlcmd
而不是
SSMS
。很好的发现!遗憾的是,SSMS不支持它,但对未来来说,这是一件非常有价值的事情。谢谢
GO
IF @@TRANCOUNT=0 BEGIN
    SET FMTONLY ON
END
EXEC sp_executesql N'/*Code that needs to be in its own batch*/'
GO
begin transaction
go
set xact_abort on
go
create table T(ID int not null,constraint CK_ID check (ID=4))
go
insert into T(ID) values (3)
go
rollback
Msg 547, Level 16, State 0, Line 7
The INSERT statement conflicted with the CHECK constraint "CK_ID". The conflict occurred in database "TestDB", table "dbo.T", column 'ID'.
Msg 3903, Level 16, State 1, Line 9
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
sqlcmd -b -E -i Abortable.sql -S .\SQL2014 -d TestDB
Msg 547, Level 16, State 1, Server .\SQL2014, Line 1
The INSERT statement conflicted with the CHECK constraint "CK_ID". The conflict
occurred in database "TestDB", table "dbo.T", column 'ID'.