I want to check if a SQL job is currently running. Is the "run_status" column the correct one to check? Is there a simpler way of doing this without having to loop through each column?
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;
}
}
}