以编程方式创建SQL Server代理作业

时间:2016-02-01 16:49:42

标签: c# sql-server sql-server-agent

我想以编程方式创建SQL Server代理作业。我使用以下代码,而运行它不会抛出任何错误,但当我检查SQL Server代理时,我没有看到任何作业。

问题1:这是从msdb数据库etgv125p (my database)创建作业的正确方法吗?

connectionStringInitial Catalog=msdb一起使用时,我收到错误

  

对象'CreateSQLAgentjobs',数据库'msdb',架构'dbo'

上的EXECUTE权限被拒绝

问题2:我需要什么类型的凭证?我已经是管理员了。

代码:

static void Main(string[] args)
{
    string connetionString = "Data Source=SERVER;Initial Catalog=etgv125p;User ID=USER;Password=PASSWORD;Application Name=LOCAL";
    //string connetionString = "Data Source=SERVER;Initial Catalog=msdb;User ID=USER;Password=PASSWORD;Application Name=LOCAL";

    SqlConnection cnn = new SqlConnection(connetionString);
    SqlCommand cmd = new SqlCommand();

    string job = "Test_Job";
    string command = "Test_StoredProc";
    string serverName = "SERVERNAME";
    string startDate = DateTime.Now.ToShortDateString();
    string startTime = DateTime.Now.TimeOfDay.ToString();

    try
    {
        cmd.CommandText = "CreateSQLAgentjobs";
        cmd.Parameters.AddWithValue("@job", job);
        cmd.Parameters.AddWithValue("@mycommand", command);
        cmd.Parameters.AddWithValue("@servername", serverName);
        cmd.Parameters.AddWithValue("@startdate", startDate);
        cmd.Parameters.AddWithValue("@starttime", startTime);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = cnn;

        cnn.Open();
        cmd.ExecuteNonQuery();   // Error when using msdb connection string.
        cnn.Close();
    }
    catch (Exception ex)
    {
        // ignored
    }
}

存储过程:

ALTER PROCEDURE CreateSQLAgentjobs 
@job NVARCHAR(128),
@mycommand NVARCHAR(max), 
@servername NVARCHAR(28),
@startdate NVARCHAR(8),
@starttime NVARCHAR(8)
AS
BEGIN TRY
    BEGIN TRAN

    GRANT EXEC on CreateSQLAgentjobs to PUBLIC
    --1. Add a job
    EXEC msdb.dbo.sp_add_job
        @job_name = @job

    --2. Add a job step named process step. This step runs the stored procedure
    EXEC msdb.dbo.sp_add_jobstep
        @job_name = @job,
        @step_name = N'process step',
        @subsystem = N'TSQL',
        @command = @mycommand

    --3. Schedule the job at a specified date and time
    EXEC msdb.dbo.sp_add_jobschedule @job_name = @job,
        @name = 'MySchedule',
        @freq_type=1,
        @active_start_date = @startdate,
        @active_start_time = @starttime

    --4. Add the job to the SQL Server 
    EXEC msdb.dbo.sp_add_jobserver
        @job_name =  @job,
        @server_name = @servername
    COMMIT TRAN
END TRY
BEGIN CATCH
    SELECT ERROR_Message(), ERROR_Line();
    ROLLBACK TRAN
END CATCH

1 个答案:

答案 0 :(得分:0)

您看到的错误EXECUTE权限被拒绝....请打开SSMS并在查询选项卡上执行以下代码:

GRANT EXEC on CreateSQLAgentjobs to PUBLIC

并将其从proc

中删除