小编典典

如果查询完成但有错误,是否需要回滚?

sql

我有这样的查询:

use DataIncremental
go
DECLARE @row_terminator CHAR;
SET @row_terminator = CHAR(10); -- or char(10)

BEGIN TRAN tran2


DECLARE @stmt NVARCHAR(2000);
SET @stmt = '
  BULK INSERT accn_adjustments
   FROM ''C:\Users\agordon\Desktop\incrementaljan2012\accn_adjustments_201112302112.txt''
   WITH 
      (
        firstrow=2,
FIELDTERMINATOR = ''|''  ,
ROWS_PER_BATCH=10000
   ,ROWTERMINATOR='''+@row_terminator+'''
   )'
exec sp_executesql @stmt;
SET @stmt = '
  BULK INSERT accn_adjustments
   FROM ''C:\Users\agordon\Desktop\incrementaljan2012\accn_adjustments_201112312112.txt''
   WITH 
      (
        firstrow=2,
FIELDTERMINATOR = ''|''  ,
ROWS_PER_BATCH=10000
   ,ROWTERMINATOR='''+@row_terminator+'''
   )'
exec sp_executesql @stmt;
SET @stmt = '
  BULK INSERT accn_adjustments
   FROM ''C:\Users\agordon\Desktop\incrementaljan2012\accn_adjustments_201201022101.txt''
   WITH 
      (
        firstrow=2,
FIELDTERMINATOR = ''|''  ,
ROWS_PER_BATCH=10000
   ,ROWTERMINATOR='''+@row_terminator+'''
   )'
exec sp_executesql @stmt;
SET @stmt = '
  BULK INSERT accn_adjustments
   FROM ''C:\Users\agordon\Desktop\incrementaljan2012\accn_adjustments_201201032101.txt''
   WITH 
      (
        firstrow=2,
FIELDTERMINATOR = ''|''  ,
ROWS_PER_BATCH=10000
   ,ROWTERMINATOR='''+@row_terminator+'''
   )'
exec sp_executesql @stmt;

begin tran tran2这样做的原因是为了确保如果有错误,我可以做一个rollback

我运行了代码,得到的消息是 "query completed with errors"

SSMS并未rows were inserted像平常那样声明某些内容。

当我尝试执行a时rollback tran tran2,它表示该交易从未开始

所以我的问题是, 是否 已提交到数据库?

如果不是,那么为什么它只说“由于错误而导致查询未完成”呢?


阅读 134

收藏
2021-03-08

共1个答案

小编典典

描述

从SQL Server 2005开始,您可以使用以下命令进行错误处理: TRY CATCH

TRY … CATCH(Transact-SQL) 为Transact-SQL实现错误处理,类似于Microsoft Visual
C#和Microsoft Visual C ++语言中的异常处理。一组Transact-
SQL语句可以包含在TRY块中。如果TRY块中发生错误,则控制权将传递给CATCH块中包含的另一组语句。

样本

BEGIN TRY
    BEGIN TRANSACTION

     -- do something

    COMMIT TRAN -- Transaction successfull, commit!
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack if error occured
END CATCH

更多信息

2021-03-08