我在SQL Server中有一个存储过程,它从表中清除记录,每5000次提交一次:
DECLARE AuditEventCursor CURSOR FOR
SELECT E.EVENT_ID
FROM XI31AUDIT2..AUDIT_EVENT E
WHERE E.START_TIMESTAMP < GETDATE() - 14;
DECLARE @EventID VARCHAR(64);
DECLARE @DetailID INT;
DECLARE @i INT;
BEGIN
--- Initialize variables
SET @EventID = '';
SET @DetailID = -1;
SET @i = 0;
-- Open cursor for records to delete from AUDIT_EVENT
OPEN AuditEventCursor;
-- Fetch first EVENT_ID
FETCH NEXT FROM AuditEventCursor
INTO @EventID;
-- Loop while we still have records
WHILE @@FETCH_STATUS = 0
BEGIN
DELETE FROM AUDIT_EVENT
WHERE EVENT_ID = @EventID;
-- Increment counter and commit every 5000
SET @i = @i + 1;
IF @i % 5000 = 0
COMMIT;
-- Fetch next EVENT_ID
FETCH NEXT FROM AuditEventCursor
INTO @EventID;
END;
-- Close cursor
CLOSE AuditEventCursor;
DEALLOCATE AuditEventCursor;
END;
当我在SSMS中手动运行时,它运行得很好。但是,当我在SQL Server代理中将其作为作业运行时,会产生以下错误:
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION. [SQLSTATE 25000] (Error 3902).
有什么区别?我使用相同的命令执行:exec Purge_Audit
谢谢!
答案 0 :(得分:0)
试试这个
-- Change value from 0 to 1
SET @i = 1;
-- Open cursor for records to delete from AUDIT_EVENT
OPEN AuditEventCursor;
-- Fetch first EVENT_ID
FETCH NEXT FROM AuditEventCursor
INTO @EventID;
-- Loop while we still have records
WHILE @@FETCH_STATUS = 0
BEGIN
-- Begin new code
IF @i % 5000 = 1
BEGIN TRANSACTION
-- End new code