Subject | RE: [firebird-support] Triggers best practice |
---|---|
Author | Svein Erling Tysvær |
Post date | 2011-06-14T05:57:41Z |
>I have a couple of tables that have tallys and several triggers that maintain these tallys.Exactly what does these triggers do? If they do something like
>
>Some of the updates can trigger the same trigger multiple times (since firebird fires a trigger per row).
>Is this considered best practice or would a stored procedure be better?
UPDATE MyCountTable
Set MyCountValue = MyCountValue-1
WHERE MyFieldValue = OLD.MyFieldValue;
UPDATE MyCountTable
Set MyCountValue = MyCountValue+1
WHERE MyFieldValue = NEW.MyFieldValue;
then this is not ideal for concurrency (at best, it serializes updates). This, however, is good for concurrency:
INSERT INTO MyCountTable(MyFieldValue, MyCountValue)
VALUES(OLD.MyFieldValue, -1);
INSERT INTO MyCountTable(MyFieldValue, MyCountValue)
VALUES(NEW.MyFieldValue, 1);
and then have a stored procedure that you run occasionally (whether occasionally means once per hour or once per year depends on your system) that does something like (beware, not tested)
FOR SELECT MyFieldValue FROM MyCountTable
GROUP BY MyFieldValue
HAVING COUNT(*) > 1
INTO :MyFieldValue DO
BEGIN
SELECT SUM(MyCountValue) FROM MyCountTable
WHERE MyFieldValue = :MyFieldValue
INTO :MyCountValue;
DELETE
FROM MyCountTable WHERE MyFieldValue = :MyFieldValue;
IF (MyCountValue <> 0) THEN
BEGIN
INSERT INTO MyCountTable(MyFieldValue, MyCountValue)
VALUES (:MyFieldValue, :MyCountValue);
END
END
When trying to get the current count, you would then typically do
SELECT SUM(MyCountValue)
FROM MyCountTable
WHERE MyFieldValue = :MyFieldValue
but summing
MyFieldValue MyCountValue
1200 575623
1200 1
1200 -1
1200 1
is of course a lot quicker than counting 575624 rows directly in your data table.
> (don't really like to use stored procedures since it adds an extra level of maintenance)What's the difference between having triggers and stored procedures when talking about maintenance? Sure, I can see that big, stored procedures can be a nightmare to debug and maintain and that triggers are less likely to be of the same size, but I don't see how small, stored procedures covering a specific task (like putting the 16 lines I wrote above to clean up MyCountTable into a stored procedure) can be more troublesome than triggers.
HTH,
Set