SQL Transactions-两个插入

时间:2019-01-21 10:52:27

标签: sql-server tsql transactions unique-constraint

我编写了一个SQL过程,该过程将数据插入两个表中。我从begin transaction开始,但是某些数据违反了第二个表的约束,最后数据被添加到第一个表中,而不是第二个表中。我的代码有什么问题?

create procedure [dbo].[procAddConference]
    @Conf_name varchar(50),
    @Begin_date date,
    @End_date date,
    @Price money,
    @Student_disc numeric(3,2),
    @Limit int,
    @Disc numeric(3,2),
    @Until int 
as 
    set nocount on
    begin transaction;
    begin try
        IF (@Begin_date > @End_date or @Limit < 0 or @Disc <0 or @Disc >1 or @Student_disc < 0 or @Student_disc > 1)
        BEGIN 
            ; throw 52000, 'Wrong data', 1
        END

        insert into Conferences (ConferenceName, BeginDate, EndDate, Price, StudentDiscount)
        values (@Conf_name, @Begin_date, @End_date, @Price, @Student_disc)

        IF @@ERROR <> 0
        begin
            RAISERROR('Error, transaction not completed!',16,-1)
            rollback transaction;
        end     

        declare @confID INT
        set @confID = @@IDENTITY

        declare @duration int
        declare @iterator int
        set @duration = DATEDIFF(dd, @Begin_date, @End_date)
        set @iterator = 0

        while @iterator <= @duration
        begin
            insert into ConferenceDay (ConferenceID, Date, Limit) 
            values (@confID, cast(DATEADD(dd, @iterator, @Begin_date) as date), @Limit)

            IF @@ERROR <> 0 or @@ROWCOUNT = 0
            begin
                rollback transaction;
                RAISERROR('Error, transaction not completed!',16,-1)
            end

            set @iterator = @iterator + 1
        end

        commit transaction;
    END TRY
    BEGIN CATCH
        DECLARE @errorMsg nvarchar (2048) = 'Cannot add conference . Error message : ' + ERROR_MESSAGE () ;
        ; THROW 52000 , @errorMsg ,1
        rollback transaction;
    END CATCH
END

0 个答案:

没有答案