Stored Procedure and populating a Temp table from a linked Stored Procedure with parameters

后端 未结 5 2236
轻奢々
轻奢々 2020-12-19 08:02

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

相关标签:
5条回答
  • 2020-12-19 08:04

    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
    
    0 讨论(0)
  • 2020-12-19 08:05

    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;
    
    0 讨论(0)
  • 2020-12-19 08:14

    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)
    
    0 讨论(0)
  • 2020-12-19 08:15

    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

    0 讨论(0)
  • 2020-12-19 08:27

    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)
    
    0 讨论(0)
提交回复
热议问题