插入在事务中失败,但是sql server返回1行受影响?

时间:2016-04-18 15:55:59

标签: sql sql-server sql-server-2008 tsql

这是我的stored procedure

的执行流程
ALTER procedure dbo.usp_DoSomething

as

declare @Var1 int
declare @Var2 int
declare @Var3 int

select 
@Var1 = Var1,
@Var2 = Var2,
@Var3 = Var3
from Table
where  
...

BEGIN TRY
    BEGIN TRANSACTION
        /* UPDATE Table. This executes successfully */

        /* INSERT Table. This fails due to PK violation */

        COMMIT TRAN /* This does not happen */
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN /* This occurs because TRANS failed */
END CATCH

UPDATE成功运行。 INSERT失败,因此transaction将被回滚。

执行后,表格看起来正确,没有任何变化。但是当我运行SP时,我收到以下消息:

(1 row(s) affected)

(0 row(s) affected)

所以我问自己,第一个1 row(s) affected来自哪里?

然后我认为这就是原因,但我想确认一下:OUTPUT Clause (Transact-SQL)

An UPDATE, INSERT, or DELETE statement that has an OUTPUT clause will return
rows to the client even if the statement encounters errors and is rolled back.
The result should not be used if any error occurs when you run the statement.

2 个答案:

答案 0 :(得分:1)

默认情况下,除非启用SET NOCOUNT ON,否则将为每个DML语句返回rowcount。无论事务是否成功,或者回滚或提交,您的UPDATE语句都成功,因此通知(1 row(s) affected)

您提到的OUTPUT子句与它无关,因为您尚未指定它。

答案 1 :(得分:0)

使用设置变量的第一个选择可能会产生1行影响