简体   繁体   中英

Create trigger for SQLite, when new record is inserted, to delete old records

I have the table "log" in an SQLite database, where I write all my log files.

However I want to pretend the database from getting to big - and the smartest way in doing this, is by using a trigger on the insert command - at least I think so...

When a new record is inserted, a trigger shall get fired, that deletes all records older than 10 days.

Or...

When a new record is inserted, a trigger shall get fired, that deletes all old records, which exceed a specific amount (for example 1000).

I need an example code.

Kind Regards, and thx.

This will create an insert trigger that will delete anything with a create date that is more then 10 days old.

CREATE TRIGGER [TRIGGER_NAME] AFTER INSERT ON my_table
BEGIN
    DELETE FROM LOG WHERE DATE(CREATE_DATE) > DATE('now', '-10 days');
END

If you want to do something based on size like you were saying with 1000 rows you can do something like this.

CREATE TRIGGER [TRIGGER_NAME] AFTER INSERT ON my_table
BEGIN
    DELETE FROM LOG WHERE ROW_NO NOT IN 
        (SELECT TOP 1000 ROW_NO FROM LOG ORDER BY CREATE_DATE DESC);
END

This will select the 1000 newest rows and delete anything that is not in that select statement.

I have tried this approach:

CREATE TRIGGER [TRIGGER_NAME] AFTER INSERT ON my_table
BEGIN
    DELETE FROM LOG WHERE ROW_NO NOT IN 
        (SELECT TOP 1000 ROW_NO FROM LOG ORDER BY CREATE_DATE DESC);
END

and result is that i can not create a trigger due to valid syntax error that i get

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM