Share via

Openquery with parameters

Ludmil G 101 Reputation points
2022-02-24T10:03:42.497+00:00

I need to use Openquery to join a linked server. I am trying to filter the linked server by a string and I need to exclude the blank records.

DECLARE @Test1 NVARCHAR(10);
SET @Test1 = '111';
SELECT * from Test1 t1 
   JOIN OPENQUERY(TestServer, 'SELECT * FROM T2 WHERE Column1 = ''' +  @Test1 + ''' and Column2 != ''')t2 ON t1.Column3 = t2.Column3
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

3 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,061 Reputation points
    2022-02-28T02:04:00.75+00:00

    Hi @Ludmil G
    Please check this:

    DECLARE @Test1 NVARCHAR(10);  
    SET @Test1 = '111';  
    SELECT *   
    FROM Test1 t1   
    JOIN OPENQUERY(TestServer, 'SELECT * FROM T2 WHERE Column1 = ''' +  @Test1 + ''' and Column2 != ''''')t2 ON t1.Column3 = t2.Column3  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

  2. Erland Sommarskog 134.4K Reputation points MVP Volunteer Moderator
    2022-02-24T22:54:07.76+00:00

    I have some tips on how to do this without losing your sanity in my article on dynamic SQL: https://www.sommarskog.se/dynamic_sql.html#remotedata.

    Was this answer helpful?

    0 comments No comments

  3. Viorel 126.9K Reputation points
    2022-02-24T20:15:32.687+00:00

    Consider using sp_executesql according to https://learn.microsoft.com/en-US/troubleshoot/sql/admin/pass-variable-linked-server-query:

    EXEC TestServer.master.dbo.sp_executesql N'SELECT * FROM MyDatabase.dbo.T2 WHERE Column1 = @Test1 and Column2 != ''''',  
        N'@Test1 nvarchar(10)', @Test1  
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.