简体   繁体   English

使用带有动态参数的过程选择INTO动态温度表

[英]SELECT INTO dynamic temp table using procedure with dynamic parameter

I can't find a full solution to my problem. 我找不到解决我问题的完整解决方案。 I have an existing stored procedure that takes dynamic input as a parameter value. 我有一个现有的存储过程,该过程将动态输入作为参数值。 I need to execute this procedure (with a dynamic variable) and would like to somehow SELECT * INTO #mytable without having to declare the schema of the temp table. 我需要执行此过程(使用动态变量),并且希望以某种方式SELECT * INTO #mytable,而不必声明临时表的架构。

I've tried using OPENROWSET but it doesn't allow me to specify the variable (only hard-code it): 我尝试使用OPENROWSET,但不允许我指定变量(只能对其进行硬编码):

select * into #table from openrowset('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec SERVER..MYSTOREDPROCEDURE @parameter = 123')

The only other way I'm aware of is wrapping it in a string and using EXEC(@sql), but I can't figure out how to "SELECT * INTO #table" from that. 我知道的唯一其他方法是将其包装在字符串中并使用EXEC(@sql),但是我不知道如何从中“选择* INTO #table”。

What are my options? 我有什么选择? Can I create a UDF table function that can return a dynamic table? 是否可以创建可以返回动态表的UDF表函数? Doubtful... 疑...

I'm guessing here, but you'll need to do the whole thing in dynamic SQL. 我在这里猜测,但是您需要在动态SQL中完成整个操作。 So, instead, something like: 因此,类似:

DECLARE @SQL nvarchar(MAX);
DECLARE @param nvarchar(10) = 123;
SET @SQL = N'SELECT *' + NCHAR(10) +
           N'INTO #table' + NCHAR(10) +
           N'FROM OPENROWSET(''SQLNCLI'', ''Server=localhost;Trusted_Connection=yes;'', ''exec SERVER..MYSTOREDPROCEDURE @parameter = ' + QUOTENAME(@param,N'''') +N''');' + NCHAR(10) +
           N'SELECT *' + NCHAR(10) + --Of course, I assume you're doing something more complex that a SELECT *.
           N'FROM #table;';
PRINT @SQL;
EXEC sp_executesql @SQL;

I think I figured it out. 我想我知道了。 I really only had to modify the temp variable names to put the temp table into the global scope. 我真的只需要修改临时变量名称即可将临时表放入全局范围。 This works for me with my actual tables (I renamed them for the purposes of this post). 这对我的实际表很有效(出于本文的目的,我将其重命名)。

IF OBJECT_ID ('tempdb..##mytemptable') is not null drop table ##mytemptable

declare @id int = 112

declare @sql nvarchar(max) ='SELECT * INTO ##mytemptable FROM OPENROWSET(''SQLNCLI'', ''Server=localhost;Trusted_Connection=yes;'', ''exec SERVER..MyStoredProcedure @ID =' + convert(varchar(10), id) + ''')'

-- invokes and inserts into ##mytemptable
exec sp_executesql @sql

-- now I can query from the global scope
select * from ##mytemptable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM