mr_*_*air 5 sql sql-server transactions sql-server-2012
我有一个要求,我要循环 10 条记录,并将这些记录插入到事务中的 3 个不同的表中。我在 while 循环和事务中一次记录一条记录。
我的要求是,如果成功插入前 8 条记录,并且如果语句在第 9 条记录处失败,则应记录错误并继续插入第 10 条记录。
如果任何行有任何错误,存储过程不应停止。
我尝试将事务放入子 TRY-CATCH 块中,但仍然失败。
BEGIN TRY
DECLARE @TotalRecord AS INT = 10
,@LoopStartCount AS INT = 1
,@AskPkQuotationId AS INT;
--Some select stuff here
WHILE(@LoopStartCount <= @TotalRecord)
BEGIN
BEGIN TRY
BEGIN TRAN
--Do some insert update for each record.
COMMIT TRAN
END TRY
BEGIN CATCH
--Log Error and Continue with next record
END CATCH
SET @LoopStartCount = @LoopStartCount + 1;
END
END TRY
BEGIN CATCH
--Log parent error
END CATCH
Run Code Online (Sandbox Code Playgroud)
尝试如下所示的方法。在 catch 部分,您可以处理该场景。
BEGIN TRY
DECLARE @TotalRecord AS INT = 10
,@LoopStartCount AS INT = 1
,@AskPkQuotationId AS INT;
--Some select stuff here
WHILE(@LoopStartCount <= @TotalRecord)
BEGIN
BEGIN TRY
BEGIN TRAN
--Do some insert update for each record.
COMMIT TRAN
END TRY
BEGIN CATCH
--Log Error and Continue with next record
IF @@TRANCOUNT >1
BEGIN
INSERT INTO dbo.ERROR_DETAILS --INSERTING ErrorInfo INTO LOG TABLE
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
ROLLBACK TRAN
END
GOTO LOOPCOUNTER1
END CATCH
LOOPCOUNTER1:
SET @LoopStartCount = @LoopStartCount + 1;
END
END
END TRY
BEGIN CATCH
--Log parent error
END CATCH
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19137 次 |
| 最近记录: |