2013-01-01 111 views
0

我想從我的C#應用​​程序中調用SQL代理作業。調用SQL代理作業

我希望能夠。

  • 在按一下按鈕就能夠執行作業。

但我也想有一些消息,當作業完成運行或失敗。

下面的代碼sampe從另一個答案不會爲我工作,因爲我需要訪問本地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

使用ADO.NET不適合您想要做的事情。 您應該使用SQL Server Management Objects API (SMO),這在執行管理任務時是首選。

更確切地說,你應該看看SMO的Job.Start方法。有關如何使用它的文章中有一個示例。 Job類提供一些事件(例如SuccessAction)以在作業完成執行時通知您。