2012-02-20 88 views
5

如果我exec的这批:当SQL Server中的错误停止执行时?

begin transaction 
    PRINT 'start' 
    PRINT 1/0 
    PRINT 'continue' 
    drop table dbo.tblPrueba 
    select * from dbo.tblPrueba 
    PRINT 'finish' 
rollback transaction 

的输出中是这样的:

start 
Msg 8134, Level 16, State 1, Line 3 
Divide by zero error encountered. 
continue 
Msg 208, Level 16, State 1, Line 6 
Invalid object name 'dbo.tblPrueba'. 

我迫使两个错误: - 第一个:PRINT 1/0(即生成该错误:

Msg 8134, Level 16, State 1, Line 3 
Divide by zero error encountered. 

并继续执行批处理

- 第二个:

drop table dbo.tblPrueba 
select * from dbo.tblPrueba 

生成此错误:

Msg 208, Level 16, State 1, Line 6 
Invalid object name 'dbo.tblPrueba'. 

并停止批

的执行它们之间有什么不同?我在哪里可以学习那些停止执行和那些不会执行的操作?

非常感谢!

回答

9

由于第一个错误是零错误划分,this behavior depends on your ARITHABORT, ARITHIGNORE and ANSI_WARNINGS settings.

从文章:

These three SET commands give you very fine-grained control for a very small set of errors. When a division by zero or an overflow occurs, there are no less four choices.

  • No action at all, result is NULL – when ARITHIGNORE is ON.
  • Warning message, result is NULL – when all are OFF.
  • Statement-termination – when ANSI_WARNINGS is ON.
  • Batch-abortion – when ARITHABORT is ON and ANSI_WARNINGS is OFF.

至于哪些错误停止执行,哪些没有,请refer to the same article

4

,以确保所有的错误都正确处理最简单的方法是使用try/catch语句

做不到这一点,不同的错误可以声明,范围或设置而定,如ARITHxx,ANSI_WARNINGS和XACT_ABORT批则中止。这表现并讨论在"Error Handling in SQL 2000"

你可以看到不同的(无SET选项改变)本

CREATE TABLE dbo.tblPrueba (gbn int); 
GO 

BEGIN TRY 

    begin transaction 
     PRINT 'start' 
     PRINT 1/0 
     PRINT 'continue' 
     drop table dbo.tblPrueba 
     select * from dbo.tblPrueba 
     PRINT 'finish' 
    rollback transaction 

END TRY 
BEGIN CATCH 
    SELECT ERROR_MESSAGE(); 
    IF XACT_STATE() <> 0 rollback transaction 
END CATCH 

如果我跑这两次,我得到这个,因为DROP永远不会执行

Msg 2714, Level 16, State 6, Line 1
There is already an object named 'tblPrueba' in the database.

+0

@PankajGarg:如果你最终在一个CATCH块中,我会回滚。我也使用SET XACT_ABORT ON,它将会回滚 – gbn 2012-02-21 08:56:19

1

Where can I learn those that stop execution

您可以使用异常处理


Begin try 
    begin transaction 
    PRINT 'start' 
    PRINT 1/0 
    PRINT 'continue' 
    create table #t 
    ( 
     id int 
    ) 
    drop table #t 
    select * from #t 
    PRINT 'finish' 
    rollback transaction 
End Try 

Begin Catch 
    if(XACT_STATE() == 1) 
    Rollback Tran 
End Catch 

您可以使用Set XACT_ABORT ON像下面。

Set XACT_ABORT ON 
begin transaction 
    PRINT 'start' 
    PRINT 1/0 
    PRINT 'continue' 
    create table #t 
    ( 
     id int 
    ) 
    drop table #t 
    select * from #t 
    PRINT 'finish' 
rollback transaction