I have a Stored Procedure (SP) in which I pass in one value. In this SP, I am trying to create/populate a Temp Table from the result of another SP that is on a Linked/remote
With some care you could use a shared temp table:
DECLARE @Qry AS VARCHAR(MAX)
SET @Qry = 'select * into ##tempTable from openquery([the Linked server],''exec thelinkedSPname ' + @param1 + ''')'
EXEC (@Qry)
-- Now just use the shared Temp table, or I suppose you could copy it to a temp table just as you wanted it:
SELECT * INTO #tempTable FROM( SELECT * FROM ##tempTable)tbl
DROP TABLE ##tempTable
With the usual disclaimers about guarding dynamic SQL, you can do this without OPENQUERY etc. Just call sp_executesql remotely:
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'EXEC thelinkedSPname ' + @param1 + ';';
INSERT #temptable EXEC [LinkedServerName].database.dbo.sp_executesql @sql;
I think you are gonna need dynamic SQL, since you can't pass the parameter to an OPENQUERY
like that (but first visit this link) So you would have something like this:
create table #tempTable(
.
)
DECLARE @param1 VARCHAR(10), @Query VARCHAR(8000)
SET @param1 = '2011'
SET @Query = '
SELECT *
FROM OPENQUERY([Linked Server],''exec thelinkedSPname '' + @param1+''')'
INSERT INTO #tempTable
EXEC(@Query)
Two words: Dynamic Query. Try this:
DECLARE @TSQL varchar(8000)
SELECT @TSQL = 'SELECT * INTO #tempTable FROM OPENQUERY([the Linked server],''exec [the Linked server].DBName.dbo.thelinkedSPname ' + @param1 + ''')'
EXEC (@TSQL)
This is well documented here: How to pass a variable to a linked server query
I use this method quite frequently:
DECLARE @YEAR AS VARCHAR(4) SET @YEAR = 2015
DECLARE @SQL AS VARCHAR(MAX)
DECLARE @OPENQUERY AS VARCHAR(MAX)
DECLARE @LINKEDSERVER AS VARCHAR(MAX) SET @LINKEDSERVER = 'Name of Linked Server here with out brackets'
SET @SQL='
Select
tbl1.*
FROM
dbo.Table_ON_LINKED_SERVER AS tbl1
WHERE
tbl1.number_id = ''''1''''
AND YEAR(tbl1.DATETIME) = ' + @YEAR + '
AND tbl1.NAME <> ''''%JONES%''''
'''
SET @OPENQUERY = 'SELECT * INTO ##GLOBAL_TEMP_NAME FROM OPENQUERY(['+ @LINKEDSERVER +'],''' + @SQL + ')'
--SELECT @OPENQUERY
EXEC(@OPENQUERY)