Skip to content
Advertisement

Trigger to delete rows from table

I’m trying to create a Trigger for when records in a log table exceed a certain number of rows I want to start purging them by x amount of old records and keeping the new records by a certain date.

Current Query (Pseudocode):

    declare @date datetime
    SET @date = 'certaindate'

    CREATE TRIGGER PURGE_USERS ON UsersAD FOR DELETE 
    AS DELETE 
    FROM UsersAD WHERE ROWCOUNT(UsersAD) > x and updateDate < @date

    GO
    -- UPDATE: Might have to partition instead of delete.

I’m assuming you get my point but neither do I know how to create the trigger in order to start deleting the records nor do I know a good way to figure out when to delete the records.

Appreciate the help,

Thanks.

Advertisement

Answer

For those are that wondering, Instead of creating a Trigger I decided to make a Function but in SQL Server you must create a Function that will have some sort of return value which is not what I wanted in my case. So after doing some more research, turns out I’d have to make a Stored Procedure which will then be executed on a daily basis. Within my query, just implemented it so it will clean up the logs after each week since it gives me enough time to look at what happened to it within the week.

Thanks again.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement