检查 SQL 服务器作业的状态

Check Status of SQL Server 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;
                }
            }
        }

可以通过msdb数据库中的存储过程sp_help_job查看。

所以 运行:

Use msdb
go
exec dbo.sp_help_job

它将 return 所有工作详细信息,您可以在其中找到名为 current_execution_status 的一列。如果它是 1 表示它是 运行ning。您可以从 link sp_help_job

获取更多信息

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

这段代码正是我所需要的。摘自 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);