How to execute SQL Server Agent Jobs which are listed in SQL Table

前端 未结 1 1456
醉话见心
醉话见心 2021-01-24 02:21

I am trying to store all the SQL Server Agent Jobs in Table name and want to execute them based on their loading frequency.

CREATE TABLE Maintainance
(
SQLJobNa         


        
相关标签:
1条回答
  • 2021-01-24 02:49

    a) Create a proc that runs through list of procs with appropriate frequency value, executes them and updates lastrun column.

    1. Make an argument @frequency in it, pass it form outside.
    2. Filter your proc list with this argument
    3. Loop through list of procs with this "frequency" and run procs

    e.g.

    alter proc dbo.RunProcs
      @Frequency varchar(50)
    as
    begin
      declare @crProcs cursor 
    
      set @crProcs = cursor fast_forward for
      select m.ProcName
      from dbo.Maintainance m
      where m.Frequency = @Frequency
      order by 1
    
      ...
      while @@fetch_status = 0
      beign
          begin try
            exec @ProcName
            ...
            update -> succeded
            ...
          end try
          begin catch
            ...
            update -> failed
            ...
          end catch
        fetch ...
      end
    
      return 1
    end
    

    b) Create scheduled jobs to run this proc

    1. Create a job "DAILY PROCS", assign a schedule to this job to make it run every day.

      Add a job-step with T-SQL: exec dbo.RunProcs @Frequency = 'day'

    2. Create a job "WEEKLY PROCS", assign a schedule to this job to make it run every week

      Add a job-step with T-SQL: exec dbo.RunProcs @Frequency = 'week'

    3. Create a job "MONTHLY PROCS", assign a schedule to this job to make it run every month

      Add a job-step with T-SQL: exec dbo.RunProcs @Frequency = 'month'

    0 讨论(0)
提交回复
热议问题