如果批量插入失败,SQL如何回滚事务

时间:2015-11-05 15:46:29

标签: sql sql-server

我编写了一个查询来删除表中的所有行,然后从txt批量插入。如果批量插入存在问题,我不想丢失旧数据,因此我想回滚事务。

这就是我一直在尝试的:

BEGIN TRANSACTION
DELETE Users_Login
BULK INSERT Users_Login FROM '\\STRMV1234\ - Some_Table.txt'  WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2, CODEPAGE = 'ACP')
COMMIT TRANSACTION 

但如果出现错误,我会丢失表中的所有内容。我也尝试了下面的代码,它也不起作用:

BEGIN TRY
    BEGIN TRANSACTION 
        DELETE Users_Login
        BULK INSERT Users_Login FROM '\\STRMV1234\ - Some_Table.txt'  WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2, CODEPAGE = 'ACP')
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

3 个答案:

答案 0 :(得分:0)

我会尝试一下。

BEGIN TRANSACTION
DELETE FROM Users_Login
BULK INSERT Users_Login FROM '\\STRMV1234\ - Some_Table.txt'  WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2, CODEPAGE = 'ACP')

IF @@ERROR = 0  
BEGIN
COMMIT
PRINT 'GOOD'
END
ELSE
BEGIN
ROLLBACK
PRINT 'BAD'
END

答案 1 :(得分:0)

这很好用:

Begin Try

    Begin Tran
    Truncate Table data
    BULK INSERT data FROM '...\data.txt'  WITH (FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 1, CODEPAGE = 'ACP')

    if @@TRANCOUNT > 0 Commit
    print 'ok'
End Try
Begin Catch
    print 'error'
    if @@TRANCOUNT > 0 Rollback
End Catch

答案 2 :(得分:0)

最优雅的解决方案是XACT_ABORT,它基本上可以启用理智的错误处理。默认的是疯狂/不可预测。

SET XACT_ABORT ON
BEGIN TRANSACTION
DELETE ...
BULK INSERT ...
COMMIT TRANSACTION

任何错误都会导致批处理和事务处理。