SQL Server触发器中的列名无效

时间:2017-04-30 16:50:31

标签: sql sql-server triggers

如果预订被取消,我有以下代码从表中删除信息但我收到以下错误:

  

Msg 207,Level 16,State 1,Procedure trgDelBooking,Line 10
  列名称无效' BookingStatus'。

但是列名称肯定是正确的。

这是我的代码:

ALTER TRIGGER trgDelBooking
ON HVCBookings
AFTER UPDATE
AS
BEGIN
    SELECT * 
    FROM Inserted

    DELETE FROM HVCActivityBooking
    WHERE PartyID = (SELECT PartyID FROM inserted)
      AND BookingStatus = 'CANCELLED'
END
GO

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

除了列名称的问题之外,您的触发器假设inserted只有一行。这是一个非常糟糕的假设。查询应为:

DELETE FROM HVCActivityBooking
WHERE PartyID IN (SELECT PartyID FROM inserted) AND
      BookingStatus = 'CANCELLED';

当然,这并不能解决未知列问题。它只是使触发更加安全。

编辑:如果BookingStatus位于HVCBookings,那么WHERE条件可以进入子查询:

DELETE FROM HVCActivityBooking
WHERE PartyID IN (SELECT i.PartyID FROM inserted i WHERE i.BookingStatus = 'CANCELLED');