Surya Subenthiran
Surya Subenthiran

Reputation: 2217

Sync between two tables

I am working with sqlite DB in iOS. I have two tables named LEVEL and SUBJECT. LEVEL TABLESUBJECT TABLE

Now I need to sync the above two tables where the TOTALCREDITS in the LEVEL table will be updated automatically when the user add a new record in the SUBJECT table(which uses LEVELID as Foreign key).

Upvotes: 0

Views: 94

Answers (1)

CL.
CL.

Reputation: 180060

You need a trigger:

CREATE TRIGGER update_totalcredits
AFTER INSERT ON Subject
BEGIN
    UPDATE Level
    SET TotalCredits = (SELECT SUM(Credits)
                        FROM Subject
                        WHERE LevelID = NEW.LevelID)
    WHERE LevelID = NEW.LevelID;
END;

However, it might be a better idea to compute the total credits dynamically (with the SELECT SUM(... query) whenever you need them.

Upvotes: 1

Related Questions