So I have this query I use to deal with a problem between my SQL Server and a linked Oracle server. Currently there is no better solution and this solution is quick and efficient but I just don't like the fact that I have to create a temp table. I feel like the results from exec()
should be able to function as a sub query but it cannot.
My question is why? If I run exec(@OPENQUERYFULL)
I get a return of all the expected data.
At the same time I can also do INSERT #myTemp exec (@OPENQUERYFULL)
and that load the same data to a temp table. (Can also do this to a perm table).
So why can I not simple do something like this:
SELECT LT.U_ID
,LT.B_ID
,LT.T_NBR
,TMP.C_NBR
,TMP.A_ID
,TMP.L_NBR
FROM LOCAL_TABLE LT
LEFT OUTER JOIN exec(@OPENQUERYFULL) TMP
ON LT.C_NBR = TMP.C_NBR
Original working solution with temp table:
DECLARE @OPENQUERYINTRO nvarchar(4000)
DECLARE @OPENQUERYBODY nvarchar(4000)
DECLARE @SQLSERVERBODY nvarchar(4000)
DECLARE @OPENQUERYFULL nvarchar(4000)
SET @OPENQUERYINTRO = 'SELECT * FROM OPENQUERY(LINKED_SERVER,'''
SET @OPENQUERYBODY = 'SELECT C_NBR, A_ID, L_NBR FROM TABLE_NAME WHERE C_NBR IN ('
SET @SQLSERVERBODY = (
SELECT RTRIM(LTRIM(STUFF((
SELECT distinct ',' + STR([C_NBR])
FROM LOCAL_TABLE FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''))))
SET @OPENQUERYFULL = @OPENQUERYINTRO + @OPENQUERYBODY + @SQLSERVERBODY + ')'')'
IF OBJECT_ID('tempdb..#myTemp', 'U') IS NOT NULL
DROP TABLE #myTemp;
CREATE TABLE #myTemp(C_NBR varchar(10), A_ID varchar(20), L_NBR varchar(20));
INSERT #myTemp exec (@OPENQUERYFULL);
SELECT LT.U_ID
,LT.B_ID
,LT.T_NBR
,TMP.C_NBR
,TMP.A_ID
,TMP.L_NBR
FROM #myTemp TMP
LEFT OUTER JOIN LOCAL_TABLE LT
ON LT.C_NBR = TMP.C_NBR