How to update a row in another sql table using triggers

I am currently working on a Java Swing application. The application allows users to perform various types of transactions. I created several tables in MS SQL to store user data. The following is the problem I'm currently facing.

I have a table called "UList" that contains all the user information. This particular table also contains the β€œBalance” column, which will contain the user's balance. There is another table called "Deposits" in which the deposit amount will be stored.

Tables:

Ulist

╔══════╦═════════╗
β•‘ id   β•‘ balance β•‘
╠══════╬═════════╣
β•‘    1 β•‘    6000 β•‘
β•‘    2 β•‘    4000 β•‘
β•šβ•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•

Deposits

╔══════╦══════╗
β•‘ amt  β•‘   id β•‘
╠══════╬══════╣
β•‘ 1000 β•‘    2 β•‘
β•‘ 1000 β•‘    1 β•‘
β•‘  500 β•‘    1 β•‘
β•‘  500 β•‘    1 β•‘
β•šβ•β•β•β•β•β•β•©β•β•β•β•β•β•β•

, , amt / . , .

create trigger d_trigger
ON Deposits
AFTER INSERT
AS
UPDATE u set u.balance=u.balance+d.amt from UList u INNER JOIN deposits d on u.id=d.id INNER JOIN inserted i on i.id=d.id

, . 500, 500 , , , 1000, . , , , ..

!

. , Java, . , MS SQL Server.

+4
2

INNER JOIN TRIGGER . :

alter trigger d_trigger
ON Deposits
AFTER INSERT
AS
    UPDATE u 
    set u.balance=u.balance+i.amt 
    from UList u 
    INNER JOIN inserted i on i.u_Id=u.u_Id
+2

, , . , .

create trigger d_trigger
ON Deposits
AFTER INSERT
AS
UPDATE UList set balance = balance + :new.amt
WHERE id = :new.id;
0

Source: https://habr.com/ru/post/1664918/


All Articles