Search code examples
sql-serversql-agent-job

Permissions to set job Enable/Disable in SQL Server


The database user has been granted SQLAgentOperatorRole, but there are still error when set job enable/disable. The error message is:

SELECT permission was denied on the object 'sysjobs', database 'msdb', schema 'dbo'

We set the job enable/disable by sp_update_job.

Comments:

When executing the following statement, will get the error.

bool result = ObjectInstance.ExecuteStoreQuery<bool>("EXEC usp_prod_SetJobStatus @jobName={0}, @isEnable={1}", jobName, isEnable).FirstOrDefault();

But, while use the following statement, it will execute successful.

 ObjectInstance.ExecuteStoreCommand("EXEC msdb.dbo.sp_update_job @job_name={0}, @enabled={1}", jobName, isEnable);

usp_prod_SetJobStatus SP:

CREATE PROCEDURE [dbo].[usp_prod_SetJobStatus]
    @jobName VARCHAR(200),
    @isEnable BIT
AS
BEGIN
    DECLARE @jobId uniqueidentifier
    DECLARE @result BIT

    SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE name = @jobName
    IF(@jobId IS NOT NULL)
    BEGIN
        EXEC @result = msdb.dbo.sp_update_job @job_name=@jobName, @enabled=@isEnable    
    END
    ELSE
    BEGIN
        SET @result = 1
    END

    SELECT  @result
END

Solution

  • I have solved this problem. The reason is that there is no SELECT permission on sysjobs table for the user. So, we need to grant the SELECT perssion for the user.

    USE msdb
    GRANT SELECT ON msdb.dbo.sysjobs TO useName