查询挂在开始tran

时间:2017-11-01 10:12:13

标签: sql sql-server

我正在执行以下操作,但它挂了几分钟,检查sp_who说会话正在运行,没有阻止

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=3) 

BEGIN tran
    SET @intFlag = @intFlag + 1
    INSERT INTO EX_EMPLOYEE (TV_CODE) VALUES (@intFlag)
 commit tran

GO

但是,如果我删除它提交并完成

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=3) 

BEGIN 
    SET @intFlag = @intFlag + 1
    INSERT INTO EX_EMPLOYEE (TV_CODE) VALUES (@intFlag)
 commit 

GO

1 个答案:

答案 0 :(得分:6)

因为你循环

WHILE (@intFlag <=3)  BEGIN tran 
永远不会结束。无限“BEGIN TRAN”

  

WHILE设置重复执行SQL语句的条件   或声明块。

将BEGIN..END用于群组

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=3) 
BEGIN
    BEGIN tran
    SET @intFlag = @intFlag + 1
    INSERT INTO EX_EMPLOYEE (TV_CODE) VALUES (@intFlag)
    commit tran
END

DECLARE @intFlag INT
SET @intFlag = 1
BEGIN TRANSACTION
WHILE (@intFlag <=3) 
BEGIN

    SET @intFlag = @intFlag + 1
    INSERT INTO EX_EMPLOYEE (TV_CODE) VALUES (@intFlag)

END
IF @@TRANCOUNT > 0
   COMMIT TRANSACTION