未提交删除批处理

时间:2019-03-07 13:05:04

标签: sql sql-server tsql azure-sql-database

我有这样的批量删除:

SET NOCOUNT ON;
DECLARE @rows INT, @count INT, @message VARCHAR(100);
SET @rows = 1;
SET @count = 0;
WHILE @rows > 0
BEGIN
    BEGIN TRANSACTION;
delete top(100000) from Table whete T1='HU'
    SET @rows = @@ROWCOUNT;

 SET @count = @count + @rows
  RAISERROR('COUNT %d', 0, 1, @count) WITH NOWAIT
    COMMIT TRANSACTION;
END

但是此查询未提交,尝试关闭窗口(会话)后,系统询问我是否要提交事务。

我的查询错误吗?

1 个答案:

答案 0 :(得分:0)

请尝试这个。

SET NOCOUNT ON;
DECLARE @rows INT, @count INT, @message VARCHAR(100);
SET @rows = 1;
SET @count = 0;
BEGIN TRY
    BEGIN TRANSACTION;

    WHILE @rows > 0
    BEGIN
    delete top(100000) from Table whete T1='HU'
        SET @rows = @@ROWCOUNT;

     SET @count = @count + @rows
      RAISERROR('COUNT %d', 0, 1, @count) WITH NOWAIT
    END

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH

-------------例如

Declare @tbl Table(
CustomerID  INT ,
CustomerName         VARCHAR(100),
AccreditationNumber  VARCHAR(100)
)

INSERT INTO @tbl VALUES(1272,'Bree','Gold')
INSERT INTO @tbl VALUES(1272,'Bree','Gold')
INSERT INTO @tbl VALUES(1272,'Bree','Gold')

INSERT INTO @tbl VALUES(1272,'Anneke','silver')
INSERT INTO @tbl VALUES(1272,'Anneke','silver')

SET NOCOUNT ON;
DECLARE @rows INT, @count INT, @message VARCHAR(100);
SET @rows = 1;
SET @count = 0;
BEGIN TRY
    BEGIN TRANSACTION;

    WHILE @rows > 0
    BEGIN
    delete top(1) from @tbl where CustomerID=1272
        SET @rows = @@ROWCOUNT;

     SET @count = @count + @rows
      RAISERROR('COUNT %d', 0, 1, @count) WITH NOWAIT
    END

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH