sql – 如何触发表以更改另一个表列的值

我创建了三个表.

CREATE TABLE Clients
(
    ClientID INT IDENTITY(1,1) PRIMARY KEY,
    First_Name VARCHAR(50) NOT NULL,
    Last_Name VARCHAR(50) NOT NULL,
)
CREATE TABLE Reservation
(
    ReservationID INT IDENTITY(1,1) PRIMARY KEY,
    ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
    Reservation_paid VARCHAR(3) DEFAULT 'NO',
)
CREATE TABLE Payment
(
    Payment_ID INT IDENTITY(1,1) PRIMARY KEY,
    ClientID INT FOREIGN KEY (ClientID) REFERENCES Clients(ClientID),
    ReservationID INT FOREIGN KEY (ReservationID) REFERENCES Reservation(ReservationID),
)

每当客户确实支付预订时,我想在Reservation表中将Reservation_paid列的值更改为YES,并且我想使用触发器自动执行此操作.

示例:如果Reservation表中的ClientID自动存在于Payment表中,则Reservation_paid的值将设置为YES.
先感谢您.

最佳答案

CREATE TRIGGER trgAfterInsert ON [dbo].[Payment] 
FOR INSERT
AS
declare @ClientID int;
select @ClientID =i.ClientID from inserted i;   

if update(ClientID)
    UPDATE Reservation set Reservation_paid='Yes' WHERE  
    ClientID=@ClientID;

--PRINT 'AFTER INSERT trigger fired.'
点赞