I have a problem with linked server query from SQL Agent job. Linked server connection working fine. But while executing query from sql agent job it fails.
Microsoft OLE DB Provider for SQL Server: Login failed for user
I used current context credential. All fine from linked server settings. But, I can not run the query from SQL Agent job.
Best Answer
When you run the SQL Server Agent job, it executes the query using the credentials of the account for which the SQL Server Agent service is running.
For linked servers and utilizing Windows Authentication, it has been my experience that it is necessary to set up the Keberos authentication for the service accounts in Active Directory, and set the Service Provider Name (SPN) by running the SETSPN command for the SQL Server service account for the SQL Server machine. See this article: https://technet.microsoft.com/en-us/library/bb735885.aspx
If you are using the SQL Authentication, I would recommend trying to log in using the account that the SQL Server Agent service uses and seeing if the query utilizing the Linked Server works correctly.
I found this code a while back, and I don't remember exactly where. So, I can't give proper credit. It should generate the code to set the SPNs if they aren't done correctly.