存储过程并使用参数从链接的存储过程填充Temp表

R M*_*R M 6 sql-server stored-procedures linked-server

我有一个存储过程(SP),我传入一个值.在此SP中,我尝试从链接/远程服务器上的另一个SP的结果创建/填充临时表.那就是我试图在我的SP中执行SP并填充我的查询将使用的临时表.

我尝试使用以下语法,但它不起作用,因为看起来openquery不喜欢"+"或@param1参数.

select * into #tempTable
from openquery([the Linked server],'exec thelinkedSPname ' + @param1)
Run Code Online (Sandbox Code Playgroud)

如果我在其中硬编码参数值,它可以正常工作.

select * into #tempTable
from openquery([the Linked server],'exec thelinkedSPname 2011')
Run Code Online (Sandbox Code Playgroud)

我也已经手动构建临时表并尝试执行链接的SP,但这也不起作用.

create table #tempTable(
.
.
.
)

insert into #tempTable
(
.
.
.
)
Exec [the Linked server],'exec thelinkedSPname ' + @param1
Run Code Online (Sandbox Code Playgroud)

有关如何从通过链接服务器执行SP的SP中填充临时表的任何建议.注意上面的SQL只是伪代码

Lam*_*mak 6

我认为你将需要动态SQL,因为你不能将参数传递给OPENQUERY那样的(但首先访问此链接)所以你会有这样的事情:

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)
Run Code Online (Sandbox Code Playgroud)


Kas*_*ash 0

两个词:动态查询。尝试这个:

DECLARE @TSQL varchar(8000)
SELECT  @TSQL = 'SELECT * INTO #tempTable FROM OPENQUERY([the Linked server],''exec [the Linked server].DBName.dbo.thelinkedSPname ' + @param1 + ''')'
EXEC (@TSQL)
Run Code Online (Sandbox Code Playgroud)

这里有详细记录: 如何将变量传递给链接服务器查询

  • 这样操作员将无法使用#tempTable,因为他无法获得这些结果 (5认同)