Now we all know that having SQL Server Agent jobs owned by ‘Real’ users isn’t a good idea. But I don’t keep that close an eye on some of our test instances, so wasn’t surprised when I spotted this showing up in the monitoring:
The job failed. Unable to determine if the owner (OldDeveloper) of job important_server_job has server access (reason: Could not obtain information about Windows NT group/user 'OldDeveloper', error code 0x534. [SQLSTATE 42000] (Error 15404)).
Wanting to fix this as quickly and simply as possible I just wanted to bulk move them to our job owning account (let’s use the imaginative name of ‘JobOwner’).
I have 2 ways of doing this quickly. First up is an old T-SQL script I wrote years back (yeah, this happens all the time)). In this case we’re looking for all the jobs owner by the user OldDeveloper
and moving them to the JobAccount
user. It uses a cursor, but they aren’t always the spawn of evil 🙂
DECLARE @job_id char(36) DECLARE JobCursor CURSOR FOR SELECT job_id FROM msdb..sysjobs sj INNER JOIN sys.server_principals sp on sj.owner_sid=sp.sid WHERE sp.name = 'OldDeveloper' OPEN JobCursor FETCH NEXT FROM JobCursor INTO @job_id WHILE (@@FETCH_STATUS <> -1) BEGIN exec msdb..sp_update_job @job_name = @job_id, @owner_login_name = 'JobAccount' FETCH NEXT FROM JobCursor INTO @job_id END CLOSE JobCursor DEALLOCATE JobCursor
And then, of course, there’s a simpler dbatools method in PowerShell:
Get-DbaAgentJob -SqlInstance server\instance | Where-Object {$_.OwnerLoginName -eq 'OldDeveloper'} | Set-DbaAgentJob -OwnerLogin JobAccount
Use Get-DbaAgentJOb
to get all the SQL Agent jobs from your instance, a quick pipe through Where-Object
to filter down to just the ones with a ‘bad’ owner, and finally into Set-DbaAgentJob
to set the new owner login.
You can use whichever you prefer as they’ll do the same job. I find the PowerShell/dbatools the easiest one as I can remember the syntax, the T-SQL one I have to remember where I left the original copy 😉