检查SQL Server作业的状态

时间:2017-06-02 12:01:54

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

我想检查一个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;
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

这段代码就是我所需要的。取自MSDN

感谢@JeroenMostert

SELECT sj.Name, 
    CASE
        WHEN sja.start_execution_date IS NULL THEN 'Not running'
        WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL THEN 'Running'
        WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NOT NULL THEN 'Not running'
    END AS 'RunStatus'
FROM msdb.dbo.sysjobs sj
JOIN msdb.dbo.sysjobactivity sja
ON sj.job_id = sja.job_id
WHERE session_id = (
    SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity); 

答案 1 :(得分:0)

您可以通过sp_help_job数据库中的存储过程msdb进行检查。

所以只需运行:

Use msdb
go
exec dbo.sp_help_job

它将返回所有作业详细信息,您可以在其中找到一个名为current_execution_status的列。如果它是1表示它正在运行。您可以从链接sp_help_job

获取更多信息

您也可以为存储过程提供参数。