如何执行SELECT*INTO[temp table]FROM[存储过程]?不是FROM[Table]并且没有定义[temp Table]?

选择BusinessLine中的所有数据到tmpBusLine工作正常。

select *
into tmpBusLine
from BusinessLine

我也在尝试同样的方法,但使用返回数据的存储过程并不完全相同。

select *
into tmpBusLine
from
exec getBusinessLineHistory '16 Mar 2009'

输出消息:

消息156,级别15,状态1,第2行关键字附近的语法不正确“exec”。

我读过几个创建与输出存储过程结构相同的临时表的示例,这很好,但最好不要提供任何列。


当前回答

存储过程是否只检索数据或修改数据?如果它仅用于检索,则可以将存储过程转换为函数并使用公共表表达式(CTE),而无需声明它,如下所示:

with temp as (
    select * from dbo.fnFunctionName(10, 20)
)
select col1, col2 from temp

然而,需要从CTE中检索的内容只能在一个语句中使用。你不能用temp做。。。并尝试在几行SQL之后使用它。对于更复杂的查询,可以在一个语句中包含多个CTE。

例如

with temp1020 as (
    select id from dbo.fnFunctionName(10, 20)
),
temp2030 as (
    select id from dbo.fnFunctionName(20, 30)
)
select * from temp1020 
where id not in (select id from temp2030)

其他回答

这是一个简单的2步过程:-创建临时表-插入临时表。

执行相同操作的代码:

CREATE TABLE #tempTable (Column1 int, Column2 varchar(max));
INSERT INTO #tempTable 
EXEC [app].[Sproc_name]
@param1 = 1,
@param2 =2;

另一种方法是创建一个类型,然后使用PIPELINED传递回对象。然而,这仅限于了解列。但它的优点是能够做到:

SELECT * 
FROM TABLE(CAST(f$my_functions('8028767') AS my_tab_type))
Select @@ServerName
EXEC sp_serveroption @@ServerName, 'DATA ACCESS', TRUE

SELECT  *
INTO    #tmpTable
FROM    OPENQUERY(YOURSERVERNAME, 'EXEC db.schema.sproc 1')

最简单的解决方案:创建表#temp(…);插入#tempEXEC[sproc];

如果您不知道模式,那么可以执行以下操作。请注意,这种方法存在严重的安全风险。

SELECT * 
INTO #temp
FROM OPENROWSET('SQLNCLI', 
                'Server=localhost;Trusted_Connection=yes;', 
                'EXEC [db].[schema].[sproc]')

存储过程是否只检索数据或修改数据?如果它仅用于检索,则可以将存储过程转换为函数并使用公共表表达式(CTE),而无需声明它,如下所示:

with temp as (
    select * from dbo.fnFunctionName(10, 20)
)
select col1, col2 from temp

然而,需要从CTE中检索的内容只能在一个语句中使用。你不能用temp做。。。并尝试在几行SQL之后使用它。对于更复杂的查询,可以在一个语句中包含多个CTE。

例如

with temp1020 as (
    select id from dbo.fnFunctionName(10, 20)
),
temp2030 as (
    select id from dbo.fnFunctionName(20, 30)
)
select * from temp1020 
where id not in (select id from temp2030)