Tuesday, 23 June 2020

[SQL Server] Use "USE Command" with OPENQUERY to Linked Server

[SQL Server] Use "USE Command" with OPENQUERY to Linked Server

Sometimes, you have to use "USE Command" with OPENQUERY to Linked Server.

Maybe you already tried this.
SELECT * FROM OPENQUERY
 (LinkedServer]
 ,'USE AdventureWorks2016;
 EXEC dbo.usp_test1;')
;

But it does not work.
You see the following error message.
Msg 7357, Level 16, State 1, Line 12
Cannot process the object "USE AdventureWorks2016; EXEC dbo.usp_test1;". The OLE DB provider "SQLNCLI11" for linked server

 "LinkedServer" indicates that either the object has no columns or the current user does not have permissions on that object.


You can use "USE Command" by wrapping with "EXEC" command like this.

SELECT * FROM OPENQUERY
       ([LinkedServer],'
       EXEC (
             ''USE AdventureWorks2016;
             EXEC dbo.usp_test1;''
             );'
       )
;


This will work.



No comments:

Post a Comment

(KOR) AI와 지속 가능한 엔지니어링 — 생성은 빠르게, 검증은 철저하게

영어 원문 : https://www.linkedin.com/pulse/ai-sustainable-engineering-generate-fast-verify-thoroughly-yoon-hclqf/ [공지 / 면책 조항] 이 글에 표현된 모든 견해는 전...