Help with Trigger that adds / subtracts

0

I need help to create a Trigger in SQL Server that takes a value INTEIRO , and two STRING(FK) , inserted in a tabela X , and check if the second value is 1 or 2 , if for 1 it must add this value INTEIRO to a value INTEIRO of another Tabela Y that has STRING(FK) as PK , and if the first String is 2 instead of adding it should subtract from the same location.

I'm having a hard time in the logic and structure of Trigger. Thanks for any help.

DETAIL (from author's comment)
There are two tables: Conta and Transação . The Conta table has the saldo column and the Transação table has the columns valorDaTransacao , tipoTransacao (1 for withdraw and 0 for deposit) and numeroConta , which is foreign key pointing to table Conta . Whenever a new row is created in the Transação table, the trigger procedure should be triggered by subtracting or adding valorTransacao in the saldo column of the Conta table.     

asked by anonymous 01.07.2017 / 05:25

1 answer

1

The trigger procedure is then to monitor the inclusion of rows in the Transaction table.

-- código #1 v2
CREATE TRIGGER incTransacao_Conta
    on Transacao 
    after INSERT as
begin
-- encerra o processamento se não há linha para tratar
IF not exists (SELECT * from INSERTED) return;
--
UPDATE C
  set saldo+= case I.tipoTransacao 
                   when 1 then -I.valorDaTransacao 
                   when 0 then I.valorDaTransacao 
                   else 0 end
  from Conta as C 
       inner join INSERTED as I on I.numeroConta = C.numeroConta;
end;

Suggested reading:

02.07.2017 / 15:21