【问题标题】:Invoking SQL Agent Jobs调用 SQL 代理作业
【发布时间】:2013-01-01 21:51:02
【问题描述】:

我正在尝试从我的 C# 应用程序调用 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();
}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多