I have the following query, which pulls data from an Oracle DB into SQL Server 2005:
SELECT *
FROM (
SELECT *
FROM OPENQUERY(LINKEDSERVERNAME, 'SELECT FOO, BAR, FROM TABLE
WHERE ID IN(' + @IDs + '
')) AS TMP
WHERE SOME_ID IN
(SELECT DISTINCT ID
FROM LOCALTABLE);
The runtime, however, is very long, as the query from the linked server results in a large number of rows. I am only interested in a small number of these rows, however the criteria limiting my query are held in the destination database.
Via another post on SO, I see I could potentially use a variable in dynamic sql that looks like:
DECLARE @IDs AS NVARCHAR(100);
SET @IDs = (SELECT ID FROM LOCALTABLE)
DECLARE @sql AS NVARCHAR(3000);
SET @sql = 'SELECT * FROM OPENQUERY(LINKEDSERVERNAME, ''SELECT FOO, BAR, FROM TABLE
WHERE ID IN(' + @IDs + '))'
EXEC sp_executesql @sql
However, I obviously cannot assign more than one value to the variable, and so the result set only contains results for the final ID placed in @IDs.
What is the best strategy for accomplishing this task for all distinct IDs in the local table?