SQL How to sum from another table and insert in another table

前端 未结 2 756
小蘑菇
小蘑菇 2021-01-29 12:11

For now I sum in Delphi app and then insert it in SQL database
but I want database to sum and insert automatically when I insert new ExpenseA

2条回答
  •  难免孤独
    2021-01-29 12:18

    Add this trigger to your ExpenseTable

    CREATE TRIGGER ExpenseSum AFTER INSERT ON ExpenseTable FOR EACH ROW
    BEGIN
        UPDATE ProjectsTable P
        SET ExpenseTotal = 
        (SELECT SUM(ExpenseAmount) from ExpenseTable
        where ExpenseTable.ProjectID= P.ProjectID)
        where P.ProjectID = New.ProjectID;
    END
    

    Don't forget to add trigger After Update and After Delete to update ExpenseTotal

提交回复
热议问题