Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server批处理错误处理问题_Sql_Sql Server_Tsql_Error Handling_Transactions - Fatal编程技术网

SQL Server批处理错误处理问题

SQL Server批处理错误处理问题,sql,sql-server,tsql,error-handling,transactions,Sql,Sql Server,Tsql,Error Handling,Transactions,如何让这批SQL在最后到达回滚事务部分?SQL只是在错误代码行上停止脚本执行。我知道我可以使用try/catch构造,但我更感兴趣的是在SQL添加try/catch之前是如何处理的 BEGIN TRAN CREATE TABLE TempTable (c1 INT NULL) INSERT INTO TempTable (c1) SELECT 1 INSERT INTO TempTable (c1) SELECT 'ABS' IF (@@ERROR = 0) BEGIN PRI

如何让这批SQL在最后到达回滚事务部分?SQL只是在错误代码行上停止脚本执行。我知道我可以使用try/catch构造,但我更感兴趣的是在SQL添加try/catch之前是如何处理的

BEGIN TRAN

CREATE TABLE TempTable (c1 INT NULL)

INSERT INTO TempTable (c1) SELECT 1

INSERT INTO TempTable (c1) SELECT 'ABS'

IF (@@ERROR = 0) 
BEGIN
    PRINT 'no error'
    COMMIT TRAN
END
    ELSE
BEGIN
    PRINT 'error' -- Why does it never get here???????
    ROLLBACK TRAN
END

在本例中,您的“ABS”正在批量中止,因为这是一个强制转换错误。 此处解释,在

你必须读这篇文章。对于SQL错误处理,您需要了解的信息比以往任何时候都多

此外,您还必须测试每个语句。如果第一次插入失败,您仍将继续执行(除非您启用了XACT_ABORT)

BEGIN TRAN

CREATE TABLE TempTable (c1 INT NULL)

INSERT INTO TempTable (c1) SELECT 1
IF @@ERROR <> 0
    GOTO errhandler

INSERT INTO TempTable (c1) SELECT 'ABS'
IF @@ERROR <> 0
    GOTO errhandler

PRINT 'no error'
COMMIT TRAN
GOTO exitpoint

errhandler:
PRINT 'error' -- Why does it never get here???????
ROLLBACK TRAN

exitpoint:

在本例中,您的“ABS”正在批量中止,因为这是一个强制转换错误。 此处解释,在

你必须阅读这篇文章。比你需要了解的更多关于SQL错误处理的知识

此外,您还必须测试每个语句。如果第一次插入失败,您仍将继续执行(除非您启用了XACT_ABORT)

BEGIN TRAN

CREATE TABLE TempTable (c1 INT NULL)

INSERT INTO TempTable (c1) SELECT 1
IF @@ERROR <> 0
    GOTO errhandler

INSERT INTO TempTable (c1) SELECT 'ABS'
IF @@ERROR <> 0
    GOTO errhandler

PRINT 'no error'
COMMIT TRAN
GOTO exitpoint

errhandler:
PRINT 'error' -- Why does it never get here???????
ROLLBACK TRAN

exitpoint: