Thursday, February 3, 2011

SQLite: inserts or updates on counts with triggers

If a record for the summary does not exist we need to insert a record with zero count and then up the count with 1. How to do this.... here the SQLite if then else version.


DROP TRIGGER IF EXISTS "trigger_year_action_summary" ;
CREATE TRIGGER "trigger_year_action_summary" AFTER INSERT ON "AUDIT_RECORD" FOR EACH ROW
BEGIN

INSERT INTO SUMMARIES ('VALUE','YEAR','MONTH','ENVIRONMENT','ACTION','USER','SUCCESS','HOUR_OF_DAY')
SELECT 0,new.YEAR,new.MONTH,new.ENVIRONMENT,new.ACTION,null,null,null
WHERE NOT EXISTS (
SELECT 1 FROM SUMMARIES WHERE
MONTH = new.MONTH
and ACTION = new.ACTION
and YEAR = new.YEAR
and environment = new.ENVIRONMENT
and success is null
and user is null
and hour_of_day is null
and day_of_week is null

);

UPDATE SUMMARIES
SET value = value + 1
WHERE
MONTH = new.MONTH
and ACTION = new.ACTION
and YEAR = new.YEAR
and environment = new.ENVIRONMENT
and success is null
and user is null
and hour_of_day is null
and day_of_week is null
;

END;

No comments:

Post a Comment