记录交易状态提交/回滚

时间:2018-11-30 16:24:44

标签: sql transactions sql-server-2016

我有多个delete语句,它们看起来与下面的内容相似。但是,我想记录每个表删除的row_count以及事务状态。 如何获得事务中的删除是否成功完成并将其记录在我拥有的Delete_Log_table中的信息。另外,如果删除失败,我将不得不停止删除操作。

请帮助:

BEGIN TRANSACTION 

DELETE FROM [DB].[SCHEMA].[EXAMPLE_TABLE]
WHERE MY_ID IN (SELECT MY_ID FROM #TEMP_TABLE)

COMMIT TRANSACTION

INSERT INTO [DELETE_LOG_TABLE] 
(TABLE_NAME, ROW_COUNT_DELETED, STATUS_OF_TRANSACTION, LOAD_DATE)
('EXAMPLE_TABLE',@@ROWCOUNT, 'HOW DO I GET COMMIT/ROLLBACK HERE- HELP', GETDATE())

1 个答案:

答案 0 :(得分:0)

您需要使用TRYCATCH来满足需要。这是您的示例:

BEGIN TRY
    BEGIN TRANSACTION 

    DELETE FROM [DB].[SCHEMA].[EXAMPLE_TABLE]
    WHERE MY_ID IN (SELECT MY_ID FROM #TEMP_TABLE)

    INSERT INTO [DELETE_LOG_TABLE] 
    (TABLE_NAME, ROW_COUNT_DELETED, STATUS_OF_TRANSACTION, LOAD_DATE)
    ('EXAMPLE_TABLE',@@ROWCOUNT, 'Successful', GETDATE())

    COMMIT TRANSACTION

END TRY
BEGIN CATCH

    INSERT INTO [DELETE_LOG_TABLE] 
    (TABLE_NAME, ROW_COUNT_DELETED, STATUS_OF_TRANSACTION, LOAD_DATE)
    ('EXAMPLE_TABLE',0, 'Error. Detail is :'+ERROR_MESSAGE(), GETDATE())


    ROLLBACK TRANSACTION
END CATCH