运行 SqlAgent 作业时出现权限问题

Permissions issue while running SqlAgent Job

当我尝试 运行 一个 Sql 代理作业时,我正在检查是否没有同时 运行ning 的先前实例。查询如下:

IF NOT EXISTS(SELECT
                            1
                        FROM msdb.dbo.sysjobactivity ja 
                        LEFT JOIN msdb.dbo.sysjobhistory jh 
                            ON ja.job_history_id = jh.instance_id
                        JOIN msdb.dbo.sysjobs j 
                        ON ja.job_id = j.job_id
                        JOIN msdb.dbo.sysjobsteps js
                            ON ja.job_id = js.job_id
                            AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id
                        WHERE ja.session_id = (SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC)
                        AND j.name = N'JobName' 
                        AND start_execution_date is not null
                        AND stop_execution_date is null
                 )
                BEGIN   
                -- code to run the job
                END

但是,我收到一个错误

The SELECT permission was denied on the object 'syssessions', database 'msdb', schema 'dbo'. [SQLSTATE 42000] (Error 229).

步骤失败。具有 sysadmin 权限的帐户是 运行 的作业步骤。

我也尝试在 msdb 数据库中为帐户提供 db_owner 权限。仍然,面临同样的问题。

你能指导我如何解决这个权限问题吗?

我认为你不需要手动检查是否有其他实例 运行ning.

示例作业的步骤:

SELECT 1;
WAITFOR DELAY '00:00:45';

并尝试 运行 两次:

EXEC msdb.dbo.sp_start_job 'job'
-- Job 'job' started successfully.

EXEC msdb.dbo.sp_start_job 'job'

Msg 22022, Level 16, State 1, Line 3

SQLServerAgent Error: Request to run job Job () refused because the job is already running from a request by <>.