新触发,需要修改

时间:2012-11-22 23:45:06

标签: sql sql-server triggers

两个表:

    Customer: Cus_ID, Status
    Payment: Pay_ID, Cus_ID, PaidOrNot

要求是将“是”设置为“PaidOrNot”,然后自动将客户状态设置为“VIP”。

    CREATE TRIGGER AutoVIP

    AFTER UPDATE OR INSERT ON Payment

    BEGIN

        IF PaidOrNot = Yes
        THEN UPDATE Customer set Status = VIP

    END

我对SQL语法不太熟悉,这个触发器似乎不起作用,你能帮我修改一下吗?感谢。

2 个答案:

答案 0 :(得分:1)

对于SQL Server,请尝试以下操作:

 CREATE TRIGGER AutoVIP
 ON Payment
 AFTER UPDATE, INSERT
 AS 
   BEGIN
     DECLARE @paid VARCHAR(5)
     DECLARE @custId INT
     SET @paid = (SELECT PaidOrNot FROM INSERTED)
     SET @custId = (SELECT Cus_ID FROM INSERTED)
     IF @paid = 'Yes'
     BEGIN
       UPDATE Customer set Status = 'VIP'
        where Cus_ID = @custId;
     END;
 END;

答案 1 :(得分:1)

如果你试试这会怎么样?

我故意尽量使其尽可能不言自明。

CREATE TRIGGER AutoVIP
ON Payment
AFTER INSERT, UPDATE
AS
BEGIN
  DECLARE @PaidOrNot VARCHAR(3) -- Or whatever datatype it is really
  DECLARE @CustomerId INT -- Or whatever datatype it is
  SET @PaidOrNot = (SELECT PaidOrNot FROM INSERTED)
  SET @CustomerId = (SELECT Cus_ID FROM INSERTED)
  IF @PaidOrNot = 'Yes'
  BEGIN
    UPDATE Customer set Status = VIP WHERE Cus_ID = @CustomerId
  END
END