如何执行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”。

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


当前回答

嗯,您确实需要创建一个临时表,但它不需要有正确的模式。。。。我创建了一个存储过程,它修改了现有的临时表,使其具有正确的数据类型和顺序(删除所有现有列,添加新列)所需的列:

GO
create procedure #TempTableForSP(@tableId int, @procedureId int)  
as   
begin  
    declare @tableName varchar(max) =  (select name  
                                        from tempdb.sys.tables 
                                        where object_id = @tableId
                                        );    
    declare @tsql nvarchar(max);    
    declare @tempId nvarchar(max) = newid();      
    set @tsql = '    
    declare @drop nvarchar(max) = (select  ''alter table tempdb.dbo.' + @tableName 
            +  ' drop column ''  + quotename(c.name) + '';''+ char(10)  
                                   from tempdb.sys.columns c   
                                   where c.object_id =  ' + 
                                         cast(@tableId as varchar(max)) + '  
                                   for xml path('''')  
                                  )    
    alter table tempdb.dbo.' + @tableName + ' add ' + QUOTENAME(@tempId) + ' int;
    exec sp_executeSQL @drop;    
    declare @add nvarchar(max) = (    
                                select ''alter table ' + @tableName 
                                      + ' add '' + name 
                                      + '' '' + system_type_name 
                           + case when d.is_nullable=1 then '' null '' else '''' end 
                                      + char(10)   
                              from sys.dm_exec_describe_first_result_set_for_object(' 
                               + cast(@procedureId as varchar(max)) + ', 0) d  
                                order by column_ordinal  
                                for xml path(''''))    

    execute sp_executeSQL  @add;    
    alter table '  + @tableName + ' drop column ' + quotename(@tempId) + '  ';      
    execute sp_executeSQL @tsql;  
end         
GO

create table #exampleTable (pk int);

declare @tableId int = object_Id('tempdb..#exampleTable')
declare @procedureId int = object_id('examplestoredProcedure')

exec #TempTableForSP @tableId, @procedureId;

insert into #exampleTable
exec examplestoredProcedure

请注意,如果sys.dm_exec_descript_first_result_set_for_object无法确定存储过程的结果(例如,如果它使用临时表),则这将不起作用。

其他回答

为了将存储过程的第一个记录集插入到临时表中,您需要了解以下内容:

只能将存储过程的第一行集插入到临时表中存储过程不能执行动态T-SQL语句(sp_executesql)您需要首先定义临时表的结构

以上内容看起来可能是限制,但IMHO完全有意义-如果您使用sp_executesql,则可以一次返回两列,一次返回十列,如果您有多个结果集,则不能将它们插入多个表中-您可以在一个T-SQL语句中的两个表中插入最大值(使用OUTPUT子句,不使用触发器)。

因此,问题主要是如何在执行EXEC之前定义临时表结构。。。进入。。。陈述

sys.dm_exec_descript_first_result_set_for_object系统.dm_exec_descript_first_result_setsp_describe_first_result_set

第一个处理OBJECT_ID,而第二个和第三个处理Ad-hoc查询。我更喜欢使用DMV而不是sp,因为您可以使用CROSSAPPLY同时为多个过程构建临时表定义。

SELECT p.name, r.* 
FROM sys.procedures AS p
CROSS APPLY sys.dm_exec_describe_first_result_set_for_object(p.object_id, 0) AS r;

此外,请注意system_type_name字段,因为它非常有用。它存储列完整定义。例如:

smalldatetime
nvarchar(max)
uniqueidentifier
nvarchar(1000)
real
smalldatetime
decimal(18,2)

在大多数情况下,您可以直接使用它来创建表定义。

因此,我认为在大多数情况下(如果存储过程符合某些条件),您可以轻松地构建动态语句来解决这些问题(创建临时表,将存储过程结果插入其中,对数据执行所需的操作)。


注意,在某些情况下,上面的对象无法定义第一个结果集数据,例如在执行动态T-SQL语句或在存储过程中使用临时表时。

存储过程是否只检索数据或修改数据?如果它仅用于检索,则可以将存储过程转换为函数并使用公共表表达式(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)

如果查询不包含参数,请使用OpenQuery,否则使用OpenRowset。

基本的事情是根据存储过程创建模式并插入到该表中。例如。:

DECLARE @abc TABLE(
                  RequisitionTypeSourceTypeID INT
                , RequisitionTypeID INT
                , RequisitionSourcingTypeID INT
                , AutoDistOverride INT
                , AllowManagerToWithdrawDistributedReq INT
                , ResumeRequired INT
                , WarnSupplierOnDNRReqSubmission  INT
                , MSPApprovalReqd INT
                , EnableMSPSupplierCounterOffer INT
                , RequireVendorToAcceptOffer INT
                , UseCertification INT
                , UseCompetency INT
                , RequireRequisitionTemplate INT
                , CreatedByID INT
                , CreatedDate DATE
                , ModifiedByID INT
                , ModifiedDate DATE
                , UseCandidateScheduledHours INT
                , WeekEndingDayOfWeekID INT
                , AllowAutoEnroll INT
                )
INSERT INTO @abc
EXEC [dbo].[usp_MySp] 726,3
SELECT * FROM @abc

我正在使用以下模式和数据创建一个表。创建存储过程。现在我知道我的过程的结果是什么,所以我正在执行以下查询。创建表[dbo]。[tbl测试树]([Id][int]标识(1,1)不为空,[ParentId][int]NULL,[IsLeft][bit]NULL,[IsRight][bit]NULL,CONSTRAINT[PK_tblTestingTree]主键集群([Id]ASC)(PAD_INDEX=关闭,STATISTICS_NORECOMPUTE=关闭,IGNORE_DUP_KEY=关闭,ALLOW_ROW_LOCKS=打开,ALLOW_PAGE_LOCKS=开启)打开[主])在[主要]去设置IDENTITY_INSERT[dbo]。[tbl测试树]打开插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(1,NULL,NULL,空)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(2,1,1,NULL)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(3,1,NULL,1)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(4,2,1,NULL)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(5,2,NULL,1)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(6,3,1,NULL)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(7,3,NULL,1)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(8,4,1,NULL)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(9,4,NULL,1)插入[dbo]。[tblTestingTree]([Id],[ParentId],[IsLeft],[IsRight])值(10,5,1,NULL)设置IDENTITY_INSERT[dbo]。[tbl测试树]关闭值(10,5,1,NULL)设置IDENTITY_INSERT[dbo]。[tblTestingTree]打开创建过程GetDate像开始从tblTestingTree中选择Id、ParentId终止创建表tbltemp(id int,父ID int)插入tbltempexec获取日期从tbltemp中选择*;

如果要在不首先声明临时表的情况下执行此操作,可以尝试创建用户定义函数而不是存储过程,并使该用户定义函数返回表。或者,如果要使用存储过程,请尝试以下操作:

CREATE TABLE #tmpBus
(
   COL1 INT,
   COL2 INT
)

INSERT INTO #tmpBus
Exec SpGetRecords 'Params'