调用SQL代理作业

时间:2013-01-01 21:51:03

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

我正在尝试从C#Application中调用SQL代理作业。

我希望能够。

  • 按下按钮即可执行作业。

但我也希望在作业完成或失败时提供某种信息。

下面的代码示例来自另一个答案对我不起作用,因为我需要访问本地MSDB数据库。

private Dictionary<int, string> ExecutionStatusDictionary = new Dictionary<int, string>()
{
{0, "Not idle or suspended"},
{1, "Executing"},
{2, "Waiting for thread"},
{3, "Between retries"},
{4, "Idle"},
{5, "Suspended"},
{7, "Performing completion actions"}
};

public string GetStatus()
{
SqlConnection msdbConnection = new SqlConnection("Data Source=GACDTL01CR585M;Initial       Catalog=msdb;Integrated Security=SSPI");
System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();

try
{
    msdbConnection.Open();

    SqlCommand jobStatusCommand = msdbConnection.CreateCommand();

    jobStatusCommand.CommandType = CommandType.StoredProcedure;
    jobStatusCommand.CommandText = "sp_help_job";

    SqlParameter jobName = jobStatusCommand.Parameters.Add("@job_name", SqlDbType.VarChar);
    jobName.Direction = ParameterDirection.Input;
    jobName.Value = "LoadRegions";

    SqlParameter jobAspect = jobStatusCommand.Parameters.Add("@job_aspect", SqlDbType.VarChar);
    jobAspect.Direction = ParameterDirection.Input;
    jobAspect.Value = "JOB";

    SqlDataReader jobStatusReader = jobStatusCommand.ExecuteReader();

    while (jobStatusReader.Read())
    {
        resultBuilder.Append(string.Format("{0} {1}",
            jobStatusReader["name"].ToString(),
            ExecutionStatusDictionary[(int)jobStatusReader["current_execution_status"]]
        ));
    }
    jobStatusReader.Close();
}
finally
{
    msdbConnection.Close();
}

return resultBuilder.ToString();
}

1 个答案:

答案 0 :(得分:1)

使用ADO.NET不适合您想要做的事情。 您应该使用SQL Server Management Objects API (SMO),这在以这种方式执行管理任务时是首选。

更确切地说,您应该看一下SMO的Job.Start方法。文章中有一个关于如何使用它的示例。 Job类提供了一些事件(例如SuccessAction),以便在作业完成执行时通知您。

相关问题