简体   繁体   中英

Equivalent of Oracle if-else trigger on SQL Server

I want to create a sales table. When there is an update on the sales table, the data in the stock table should automatically be decreased.

This is my code in Oracle:

create trigger trigger_updatestok11
after insert
on transaksijualbeli for each row
begin
  if (:new.kategoritransaksi in ('beli'))
  then
    update stokbarang set jumlahstok= jumlahstok +:new.jumlah
    where Nobrg=:new.nobrg;
  end if;
  if (:new.kategoritransaksi in ('jual'))
  then
    update stokbarang set jumlahstok= jumlahstok -:new.jumlah
    where Nobrg=:new.nobrg;
  end if;
end;

How can I do that in SQL Server?

First of all, SQL Server triggers don't have a for each row option - the trigger is fired once per statement , and if that INSERT statement inserted more than one row, Inserted will contain more than one row. You need to write your trigger in a proper, set-based fashion, taking into account that Inserted can (and will! ) contain multiple rows - something like this:

create trigger trigger_updatestok11
after insert
on transaksijualbeli 
as
begin
    update stokbarang 
    set jumlahstok = jumlahstok + i.jumlah
    from Inserted i
    where stokbarang.Nobrg = i.nobrg
      and i.kategoritransaksi in ('beli');

    update stokbarang 
    set jumlahstok= jumlahstok - i.jumlah
    from Inserted i
    where stokbarang.Nobrg = i.nobrg
      and i.kategoritransaksi in ('jual');

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM