I have 3 tables:
transaction(IDtransaction,IDperson,IDPos,IDStore,TotalValue,Date)
items(IDtransaction,IDItem,IDproduct,Quantity)
persons(IDperson, balance)
What I am trying to accomplish is to delete from transaction when the total value is bigger that the balance of that person however it doesn't seem to work when I insert at the same time a wrong and a correct record. Why isn't working?
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