如何插入更新触发器?

时间:2015-02-16 02:38:54

标签: sql-server triggers insert-update

我知道这对你来说很简单。但是我找不到正确的。

我有2个表dbo.seatdbo.booking

这是座位表。我把所有列表座位都设置为并且设置状态为0。

this is <code>seat</code> table

这是booking表。当我执行insert时,默认情况下statusBooked为1.如果[end]等于当前时间,则statusBooked将更新为0。

this is booking table

我希望dbo.seat上的状态是{Seat} dbo.booking上的参考状态。如果statusBooked为1,则状态也为1,但当statusBooked更新为0时,状态也更新为0.

注意:在另一种情况下,由于某种原因,我处于2状态(statusBooked和status)。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

以下触发器将使用INSERT,UPDATE和DELETE来保持字段同步。

CREATE TRIGGER tg_booking_update_seat
ON dbo.booking
AFTER INSERT, UPDATE, DELETE 
AS
BEGIN
    IF EXISTS (SELECT * FROM INSERTED) BEGIN

        -- Handle insert or update
        UPDATE Sets SET
            status = Bookings.statusBooked
        FROM dbo.seat Seats
            INNER JOIN INSERTED Bookings
                ON Bookings.noSeat = Seats.noSeat

    END ELSE BEGIN
        -- Handle booking being deleted
        UPDATE Seats SET
            status = 0
        FROM dbo.seat Seats
            INNER JOIN DELETED Bookings
                ON Bookings.noSeat = Seats.noSeat
    END
END
GO

更新如果没有删除,您的触发器可以简化为:

CREATE TRIGGER tg_booking_update_seat
ON dbo.booking
AFTER INSERT, UPDATE
AS
BEGIN
    -- Handle insert or update
    UPDATE Sets SET
        status = Bookings.statusBooked
    FROM dbo.seat Seats
        INNER JOIN INSERTED Bookings
END
GO