schemazen icon indicating copy to clipboard operation
schemazen copied to clipboard

What about scripting jobs?

Open bernardoadc opened this issue 5 years ago • 3 comments

Jobs are stored in the msdb database, but inside tables, not as code explicitly. I run this snippet to get their code, but wonder if there's something better (and not doing so by hand in SSMS, one by one)

  SELECT [type] = 'JOB', [object] = J.name + ' - Step ' + convert(varchar,S.step_id) + ': ' + S.step_name, code = S.command
    FROM [msdb].[dbo].[sysjobsteps] S
   INNER JOIN [msdb].[dbo].[sysjobs] J
      ON S.job_id = J.job_id
   WHERE database_name = DB_NAME()

bernardoadc avatar May 30 '19 14:05 bernardoadc

here's a snippit from a larger Powershell process I have to script off jobs to disk...assumes $ServerName and $OutputFolder are set....dumps it all to one file...you could pipe each occurrence to its own file as well:

#Create a new SMO instance for this $ServerName
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
#Script out each SQL Server Agent Job for the server to a file with no changes as a baseline
$srv.JobServer.Jobs | foreach {$_.Script() + "GO`r`n"} | out-file "$OutputFolder\jobs$(get-date -f yyyyMMdd_HHmmss).sql"

jheimx4 avatar Sep 11 '19 20:09 jheimx4

great! thanks @jheimx4 , i'll give a try

bernardoadc avatar Sep 14 '19 02:09 bernardoadc

You could also use something like BCP to copy data in and out of job fields, I dont really think schemazen would want to go to separate databases and script out objects outside of the target.

https://docs.microsoft.com/en-us/sql/relational-databases/import-export/import-and-export-bulk-data-by-using-the-bcp-utility-sql-server?view=sql-server-ver15

ConstantineK avatar Nov 23 '19 01:11 ConstantineK