Problem:
You can run a job in SQL Server Management studio, but it fails to run with a T-SQL, and vice versa.
Analysis: In most cases, context security issues occur during execution. When executed in SSMs, The T-SQL statement is run under the current login name. However, jobs run on the SQL Server Agent service account in the SQL Server Agent, if the account of the SQL Server Agent is different from the account that executes the T-SQL in SSMs or has different permissions, the job fails. My practice is to use a high-permission account to run the SQL Server Agent, and have an independent account, and the password cannot expire, otherwise it will not run for a period of time. However, based on the "minimum security principle", it is generally not recommended to use excessive permissions. At the same time, you cannot use the SQL Server Agent agent to execute a job because the T-SQL job step does not use any proxy. For a T-SQL job step, it is run by default in the security context of the job owner. Solution: Method 1: Open the permissions of the job owner to a large enough value, but do not use SysAdmin. Method 2: run the T-SQL job with the run as user prompt in the T-SQL job. In this way, you do not need to change the original permissions. However, this process ensures that you have sufficient permissions to grant the run as user. Method 3: This method is mainly scripted method 2, in the beginning of the T-SQL:
[SQL] View plaincopyprint?
- Execute As User='Xxxx'
- -- The preceding statement grants the following script XXXX logon user permissions.
- Select*FromHumanResources. Department
- -- Revoke permissions after running:
- Revert;
Execute as user = 'xxxx' -- the preceding statement grants the following script XXXX logon user permissions. Select * From HumanResources. Department -- revoke permission after running: Revert;
Finally, you can use sqlserver profiler to monitor the accounts that execute jobs.