SQL触发器-插入后更新错误和正确的值

时间:2018-12-12 13:48:01

标签: sql-server tsql database-trigger

我有3张桌子:

transaction(IDtransaction,IDperson,IDPos,IDStore,TotalValue,Date)
items(IDtransaction,IDItem,IDproduct,Quantity)
persons(IDperson, balance)

我要完成的工作是,在总值大于该人的余额时从交易中删除,但是当我同时插入错误和正确的记录时,它似乎不起作用。为什么不起作用?

create trigger trigger4
on transaction
After insert,update
As
BEGIN   

delete transaction
FROM inserted i
where transaction.IDtransaction=i.IDtransaction AND EXISTS (select * from inserted i, persons p
                where i.IDperson=p.IDperson 
                and i.TotalValue > p.balance) 

if @@ROWCOUNT > 0
begin
print('Error!')
    if exists(select 1 from deleted) and exists (select 1 from inserted) --check if it is an update
    begin
    SET IDENTITY_INSERT transaction ON

    insert into transaction(IDtransaction,IDperson,IDPos,IDStore,TotalValue,Date)
    select d.IDtransaction,d.IDperson,d.IDPos,d.IDStore,d.TotalValue,d.Date
    from deleted d
    where d.IDtransaction not in (select t.IDtransaction from transaction t)

    SET IDENTITY_INSERT transaction OFF

    end
end             
END

1 个答案:

答案 0 :(得分:0)

我不感到惊讶,因为它不会引发语法错误,但这有点不对:

delete transaction
FROM inserted i
where transaction.IDtransaction=i.IDtransaction AND EXISTS (select * from inserted i, persons p
                where i.IDperson=p.IDperson 
                and i.TotalValue > p.balance) 

因为您不是joining inserted to transaction,所以DELETE与FROM无关。