我想檢查一個SQL作業當前是否正在運行。 「run_status」列是否正確檢查?有沒有更簡單的方法做到這一點,而不必循環通過每列?檢查SQL Server作業的狀態
public int CheckAgentJob(string connectionString, string jobName)
{
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "msdb.dbo.sp_help_jobactivity";
command.Parameters.AddWithValue("@job_name", jobName);
command.Connection = dbConnection;
using (dbConnection)
{
dbConnection.Open();
using (command)
{
SqlDataReader reader = command.ExecuteReader();
reader.Read();
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
int jobStatus = -1; // inactive
for (int i = 0; i < fieldCount; i++)
{
object item = values[i];
string colName = reader.GetName(i);
if (colName == "run_status")
{
if (values[i] != null)
{
jobStatus = (int)values[i];
break;
}
}
}
reader.Close();
return jobStatus;
}
}
}
[請不要把問題標題標籤(https://stackoverflow.com/help/tagging) – Liam
您可以查詢['msdb.dbo。 sysjobactivity'](https://docs.microsoft.com/en-us/sql/relational-databases/system-tables/dbo-sysjobactivity-transact-sql)。它被記錄在案;存儲過程只是一個很好的東西。 –
[我怎樣才能確定工作狀態?](https://stackoverflow.com/questions/200195/how-can-i-determine-the-status-of-a-job) – Liam