I would like to know how to pass a list into openquery. To use a single value the following will work:
DECLARE @TSQL varchar(8000), @VAR char(2)
SELECT @VAR = 'CA'
SELECT @TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + @VAR + ''''''')'
EXEC (@TSQL)
including parameters in OPENQUERY
However, I need to be able to use a condition like
WHERE state IN ('CA', 'TX', 'SD')
rather than = 'CA'. I have tried many things with no luck. Help is appreciated.
I tried to use the below solution but it failed.
DECLARE @list NVARCHAR(MAX)
SET @list = 'value1, value2, value3' -- Replace this with your list of values
DECLARE @sql NVARCHAR(MAX)
SET @sql = '
SELECT *
FROM OPENQUERY([YourLinkedServerName],
''SELECT *
FROM YourRemoteTable
WHERE YourColumn IN (''' + REPLACE(@list, ',', ''',''') + ''')''
)'
EXEC sp_executesql @sql
If you do a
PRINT @sql, you will see that the dynamic query iswhich is wrong. You will need to double the single quote in the dynamic query
So when forming
@sql, it should be