Skip to content

Instantly share code, notes, and snippets.

@GuildPortal
Created May 9, 2012 18:49
Show Gist options
  • Save GuildPortal/2647933 to your computer and use it in GitHub Desktop.
Save GuildPortal/2647933 to your computer and use it in GitHub Desktop.
AFTER INSERT Trigger to keep table at a specified number of rows
ALTER TRIGGER [dbo].[ErrorLog_Clean_Over_500]
ON [dbo].[ErrorLog]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @countInLog int
DECLARE @countOver500 int
SET @countInLog = (SELECT COUNT(ErrorLogID) FROM ErrorLog WITH (NOLOCK));
IF (@countInLog > 500)
BEGIN
SET @countOver500 = (@countInLog - 500);
PRINT('Deleting ' + CAST(@countOver500 AS varchar(50)) + ' rows from error log to make room.');
DELETE ErrorLog FROM (SELECT TOP (@countOver500) * FROM ErrorLog ORDER BY AddStamp) ErrorLog;
END
ELSE
BEGIN
PRINT('No need to delete any entries from the error log.');
END
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment