事务在SQL Server 2017中不起作用

时间:2018-11-15 17:41:10

标签: sql sql-server tsql transactions

我有一笔交易要检查表中的条目是否具有相同的日期和subHistoryID。不管数据是否匹配,事务总是回滚。在这个问题上的任何帮助将是巨大的。

BEGIN TRANSACTION [Tran1]
    INSERT INTO History(Name, subHistoryID, GarageID, StaffID, Date, Notes)
    VALUES (@name, @subhistoryid, @garageid, @staffid, @date, @notes);

    IF EXISTS (SELECT * FROM History 
               WHERE History.Date = @date AND History.subHistoryID = @subhistoryid) 
    BEGIN
        ROLLBACK TRANSACTION [Tran1]
        PRINT 'ERROR: Rolling back transaction.'
    END
    ELSE
    BEGIN
        PRINT 'PASS: Committing transaction.'
        COMMIT TRANSACTION [Tran1]
    END
GO

My data before attempting the transaction.

DECLARE @name varchar(20) = NULL;
DECLARE @subhistoryid int = 1;
DECLARE @garageid int = 1;
DECLARE @staffid int = 1;
DECLARE @date Date = '2018-10-21';
DECLARE @notes varchar(100) = 'test'; 

该数据应该回滚。

DECLARE @name varchar(20) = NULL;
DECLARE @subhistoryid int = 1;
DECLARE @garageid int = 1;
DECLARE @staffid int = 1;
DECLARE @date Date = '2016-1-1';
DECLARE @notes varchar(100) = 'test'; 

该数据应该提交,但会回滚

0 个答案:

没有答案