I'm trying to get the values from an external Database server executing the following code:
DECLARE @TSQL VARCHAR(8000), @VAR CHAR(2)
DECLARE @Prefixos VARCHAR(MAX);
WITH cte AS
(
SELECT DISTINCT prefixo
FROM ARH.arh.UorPos
)
SELECT @Prefixos = COALESCE(@Prefixos + ', ', '') + prefixo
FROM cte
ORDER BY prefixo
--SELECT @Prefixos --print a list of values separated by comma. eg.: 1, 2, 3
SELECT @TSQL = 'SELECT * FROM OPENQUERY(DICOI_LINKEDSERVER,''SELECT * FROM ssr.vw_sigas_diage where cd_prf_responsavel in (''''' + @Prefixos + ''''''') order by cd_prf_responsavel, codigo'
EXEC (@TSQL)
But I'm getting:
OLE DB provider "MSDASQL" for linked server "DICOI_LINKEDSERVER" returned message "ERRO: syntax error at the end of input;
No query has been executed with that handle".Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "MSDASQL" for linked server "DICOI_LINKEDSERVER".
I've researched the above links to try to resolve it:
How to concatenate text from multiple rows into a single text string in SQL server?
Join query result to a single line of values separated by comma [duplicate]
Can anyone help me to resolve it ?
Thanks in advance.