sql—事务等待提交,否则会阻塞资源

s4chpxco  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(335)

我想在事务块中放入一些语句,以便在出现任何错误时脚本回滚。我将事务与 TRY 像这样阻塞(注意 INSERT 语句(通过语法错误):

  1. begin try
  2. begin tran
  3. SET ANSI_NULLS ON
  4. SET QUOTED_IDENTIFIER ON
  5. CREATE TABLE [MY_DATABASE].[dbo].[MY_TABLE](
  6. [Id] [nchar](10) NULL,
  7. [Name] [nchar](10) NULL
  8. ) ON [PRIMARY]
  9. insert into [MY_DATABASE].[dbo].[MY_TABLE] (Id,Name) values ('1','Vampire'), ('2')
  10. commit tran
  11. end try
  12. begin catch
  13. rollback tran
  14. end catch

运行此语句后,我注意到我无法在managementstudio中获取其他表,并且操作正在等待我提交。
如何更改事务try块,以便在出现任何错误时回滚到 begin try 声明?

qij5mzcb

qij5mzcb1#

脚本尚未执行。只是语法错误导致脚本在执行前抛出错误。什么也没有开始执行。

soat7uwm

soat7uwm2#

您的脚本过早停止,而不是执行 catch 阻止。令人不满意的答案是,这是 TRY/CATCH 无法处理。
sql server启动事务,创建表,然后崩溃
msg 10709,level 16,state 1,line 117表值构造函数中每行的列数必须相同。
离开打开的事务(这就是为什么不能在mgmt studio中获取其他表)。

  1. begin try
  2. begin tran
  3. SET ANSI_NULLS ON
  4. SET QUOTED_IDENTIFIER ON
  5. CREATE TABLE [dbo].[MY_TABLE](
  6. [Id] [nchar](10) NULL,
  7. [Name] [nchar](10) NULL
  8. ) ON [PRIMARY]
  9. insert into [dbo].[MY_TABLE] (Id,Name) values ('1','Vampire'), ('2')
  10. commit tran
  11. end try
  12. begin catch
  13. print 'Now inside the "catch" block. You will not see this message.';
  14. rollback tran
  15. end catch
  16. go
  17. select * from MY_TABLE;
  18. select @@trancount as TranCount;
  19. rollback tran;

输出如下。请注意表和打开的事务的存在:

  1. Msg 10709, Level 16, State 1, Line 117
  2. The number of columns for each row in a table value constructor must be the same.
  3. Id Name
  4. ---------- ----------
  5. (0 rows affected)
  6. TranCount
  7. -----------
  8. 1
  9. (1 row affected)
展开查看全部

相关问题