SQL删除触发器

时间:2018-11-28 11:48:06

标签: sql sql-server database-trigger

我有3张桌子:

POS(IDPOS,IDCARD);

卡(IDCARD,IDPERSON);

PERSON(IDPERSON,PERSONTYPE)。

每次将卡与POS关联时,我都需要确保拥有该卡的人只能是PERSONTYPE ='Employee'或PERSONTYPE ='Volunteer'。 到目前为止,这是我完成的操作,但是当我插入有效记录时,它似乎不起作用。

DELETE POS
FROM inserted i 
INNER JOIN POS p ON i.IDPOS=p.IDPOS
INNER JOIN CARDS ON i.IDCARD=CARDS.IDCARD
INNER JOIN PERSON ON CARDS.IDPERSON=PERSON.IDPERSON
WHERE PERSONTYPE <> 'Employee' or PERSONTYPE <> 'Volunteer';

此触发器是在POS表上完成的,并且是插入后更新的。

有人知道这是错误吗?

2 个答案:

答案 0 :(得分:0)

使用NOT IN

WHERE PERSONTYPE NOT IN ('Employee', 'Volunteer');

您的逻辑要求使用AND,而不是OR

答案 1 :(得分:0)

我相信您已经为POS使用了别名,您需要为删除添加别名。您也可以使用NOT EXISTS()代替加入另一个表:

使用别名:

DELETE P
FROM POS AS P 
INNER JOIN INSERTED AS I ON i.IDPOS=p.IDPOS
INNER JOIN CARDS ON I.IDCARD=CARDS.IDCARD
WHERE NOT EXISTS (SELECT 1 
                    FROM PERSON 
                    WHERE CARDS.IDPERSON=PERSON.IDPERSON 
                    AND PERSONTYPE IN ('Employee','Volunteer')
                 );

正常用法:

DELETE 
FROM POS
INNER JOIN INSERTED AS I ON I.IDPOS=POS.IDPOS
INNER JOIN CARDS ON I.IDCARD=CARDS.IDCARD
WHERE  NOT EXISTS (SELECT 1 
                    FROM PERSON 
                    WHERE CARDS.IDPERSON=PERSON.IDPERSON 
                    AND PERSONTYPE IN ('Employee','Volunteer')
                 );