SQL Server Jobs – How to Trim Table Output for a Specific Job

jobslogsscriptingsql servertroubleshooting

I have a routine to save the logins and apply them on a different server , and I run this routine from a job that I have scheduled to run everyday.

On that job I have specified these 3 things:

  1. Log to table
  2. Append output to existing entry in table
  3. Include step output in history

as can be seen on the picture below:

enter image description here

I am happy with that, however, I was wondering if there is a way to trim the table output because when I open it I see records from over 4 months ago, which are no longer relevant now, as shown on the picture below:

when I click View:

enter image description here

I get:

enter image description here

and the table has over 61 thousand lines.

Every time the job runs it adds about 600 new lines to the bottom of the table.

Can I keep the last let's say 10 thousand lines only,getting rid of the older lines?

Best Answer

Yes.

The CommandLog cleanup is from Ola Hallengren's Maintenance Solution, so doesn't affect msdb history directly.

Use sp_purge_jobhistory, like so:

sp_purge_jobhistory   
   {   [ @job_name = ] 'job_name' |   
     | [ @job_id = ] job_id }  
   [ , [ @oldest_date = ] oldest_date ]  

Per the documentation, 'job_name' is the name of the job for which to delete the history records. Either job_id or job_name must be specified, but both cannot be specified.