【发布时间】:2017-06-02 12:01:54
【问题描述】:
我想检查 SQL 作业当前是否正在运行。 “run_status”列是要检查的正确列吗?有没有更简单的方法可以做到这一点而不必遍历每一列?
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;
}
}
}
【问题讨论】:
-
您可以直接查询
msdb.dbo.sysjobactivity。它已记录在案;存储过程只是一个细节。
标签: c# sql-server sql-agent-job