【问题标题】:Insert results of EXEC statement into temporary table without knowing the schema of results first在不知道结果模式的情况下,将 EXEC 语句的结果插入临时表
【发布时间】:2016-03-09 19:13:30
【问题描述】:

我正在使用 EXEC 语句来执行返回表值的存储过程。我想将此语句的结果插入到一个临时表中,但我不想先定义这个临时表。这可能吗?

我正在考虑SELECT * INTO #temp FROM ... 不需要首先定义#temp。是否可以对 EXEC 语句的结果做同样的事情?

【问题讨论】:

  • 这个问题已经在 SO 和互联网的其他地方被问了几十次,甚至几百次。排序答案是否定的。这是可能的,但它需要大量的跳跃才能实现。您可以使用动态 sql 和/或 openquery 来做到这一点,但它不是很可靠。

标签: sql-server tsql select insert exec


【解决方案1】:

这是您正在寻找的解决方案 -

exec sp_configure 'show advanced option',1
reconfigure
go
exec sp_configure 'ad hoc distributed queries',1
reconfigure
go

--如果没有参数,就用这个--

select * into #a
from openrowset('sqlncli','server=localhost;trusted_connection=yes','exec dbo.yourprocedure')

--如果存储过程中有参数,使用这个---

declare @sql nvarchar(max)
declare @param1 varchar(100)

set @sql = 'select * into #a
from openrowset(''sqlncli'',''server=localhost;trusted_connection=yes'',''exec dbo.yourprocedure ''' + @param1 + ')'

exec sp_executesql @sql

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2021-02-12
    • 2014-10-26
    • 2015-05-03
    • 2018-07-05
    相关资源
    最近更新 更多