dimanche 24 mai 2015

How can you implement an If statement in a SQLite trigger?

We have a self-referencing relationship defined in our SQLite database as such...

Create Table Categories{
    Id INTEGER PRIMARY KEY,
    Name TEXT NOT NULL CHECK(length(Text) > 0),
    ParentId INTEGER References Categories(Id),
    IsSelected BOOL
};

We're trying to set a trigger up on the IsSelected field to automatically propagate the values up the hierarchy.

When setting the value to True, it's easy. We simply set the trigger to set its parent to True, which in turn does the same for its parent, walking up the hierarchy until it gets to the root.

When we're setting it to False however, that logic doesn't apply because there could be another sibling of the record being changed that is still true, so its parent is still true.

So how do I do the following in a trigger? Note, this is obviously a nonsensical hybrid of SQL, C# and LINQ, but it illustrates what I'm trying to do.

CREATE TRIGGER T_Categories_IsSelectedChanged
UPDATE OF IsSelected ON Categories
BEGIN
    if(new.IsSelected)
        Update Categories Set IsSelected = True Where Id = old.ParentId;
    else
    {
        void isSiblingSelected = Categories
            .Where(c => c.ParentId = old.ParentId)
            .Any(c => c.IsSelected);

        UPDATE Categories 
        SET IsSelected = isSiblingSelected
        WHERE Id = old.ParentId;
    }
END

Aucun commentaire:

Enregistrer un commentaire