Question

New to asking questions, but have been using Stackoverflow for years.

I have two individually linked servers that do not speak to one another. I need to get a list of variables from one server into SQL and then pass that list of variables into the second OpenQuery with an end goal of bring the data from that server into SQL. I have been able to pass single keyed in variables. But when I try to use a stringed OpenQuery or just a stringed query it returns errors. Can someone point me in the right direction?

Current query:

    DECLARE @string VARCHAR(MAX)
,       @SQL NVARCHAR(MAX);

SET @string = 
'
Select 
    col1    
from 
    OpenQuery(server1, ''Select col1 from table1 where col2 = '''' a ''''
    ';
SET @SQL = 'SELECT * FROM OPENQUERY(Server2, ''SELECT * FROM table2 WHERE col1 = ''''' + @string  + ''''' '')';


EXEC sp_executesql @string;

Any Assistance you can give would be greatly appreciated.

I am using SSMS 2012 running on 2008 SQL servers. The two linked servers are Oracle servers not able to be remote connected.

No correct solution

OTHER TIPS

By nesting one openquery within another, you are telling server2 to run an openquery to server1, which you have stated you cannot do. There are also errors above, in that you are nesting @string into @sql, but you are executing @string, not @sql.

If you are expecting a relatively small return, I'd suggest using temp tables to hold the data from server1, then filter the return from server2 using that.

IF OBJECT_ID('TEMPDB..#TMP') IS NOT NULL
    DROP TABLE #TMP

SELECT COL1 
INTO #TMP 
FROM OPENQUERY(SERVER1, 'SELECT COL1 FROM TABLE1 WHERE COL2 = ''A''')

SELECT * 
FROM OPENQUERY(SERVER2, 'SELECT * FROM TABLE2')
WHERE COL1 IN (SELECT COL1 FROM #TMP)

As a followup edit, if the return from server2 is large, you should consider filtering it before it returns to your local server so you're not transferring massive amounts of data over the wire. In this case, I'd convert the values of #tmp into a comma separated string, and nest that into the 2nd openquery in a variable, and execute it with sp_executesql. Here is a great SO post on converting a column to a comma separated list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top