如何使用SELECT * INTO tempTable from CTE Query创建临时表


163

我有一个要从中创建临时表的MS SQL CTE查询。我不确定该怎么办,因为它会导致Invalid Object name错误。

下面是整个查询供参考

SELECT * INTO TEMPBLOCKEDDATES FROM 
;with Calendar as (
    select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, EventStartDate as PlannedDate
    ,EventType from EventCalender
    where EventActive = 1 AND LanguageID =1 AND EventBlockDate = 1
    union all
    select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, dateadd(dd, 1, PlannedDate)
    ,EventType from Calendar
    where EventRecurring = 1
        and dateadd(dd, 1, PlannedDate) <= EventEndDate 
)
select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
    or EventEnumDays is null
order by EventID, PlannedDate
option (maxrecursion 0)

我希望方向正确,或者可以从此CTE查询中创建临时表,


这里是如何做到这一点stackoverflow.com/questions/3306096/...
Luxspes

1
@RGI,这两个答案都适合我的情况,我给他马丁投票,因为我只能选择一个答案。感谢您的回答。我还给了您比他更优先的答案,因为您也提到了临时查询的删除部分。为您还投票。–
学习

Answers:


238

样本DDL

create table #Temp
(
    EventID int, 
    EventTitle Varchar(50), 
    EventStartDate DateTime, 
    EventEndDate DatetIme, 
    EventEnumDays int,
    EventStartTime Datetime,
    EventEndTime DateTime, 
    EventRecurring Bit, 
    EventType int
)

;WITH Calendar
AS (SELECT /*...*/)

Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
    or EventEnumDays is null

确保使用后删除该表

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

6
为什么要加倍?那是错字吗?
Mike Cole

18
..将省略指定架构。对于以前的tempdb.dbo。#temp。取而代之的是,我们可以键入tempdb ..#temp。
山姆

7
这不能回答问题。OP专门询问如何使用“选择进入”来执行此操作,但此响应没有执行该操作。这是一个很好的答案,但这不是正确的答案。
DaveInAZ

165

确实,格式可以非常简单-有时不需要预定义临时表-它将根据选择结果创建。

Select FieldA...FieldN 
into #MyTempTable 
from MyTable

因此,除非您想要不同的类型或对定义非常严格,否则请保持简单。另请注意,当存储过程完成执行时,将自动删除在存储过程内部创建的任何临时表。如果存储过程A创建了一个临时表并调用了存储过程B,则B将能够使用A创建的临时表。

但是,通常最好将明确创建的每个临时表都删除掉。


4
如果我不使用代码中的drop table删除临时表,执行后数据库中的临时表可用多长时间?因为我两次执行了代码,select * into #temp但是第二次执行传递了一个错误:“表#temp已存在于数据库中”
Kurapika '16

6
@Kurapika的连接持续时间
Jonesopolis

7
在使用表之前,我们不需要显式创建表的事实是此答案中最相关的事实。谢谢!
Alfabravo

24

SELECT ... INTO需求是在从CTE的选择。

;WITH Calendar
     AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
       EventStartDate,
       EventEndDate,
       PlannedDate                   AS [EventDates],
       Cast(PlannedDate AS DATETIME) AS DT,
       Cast(EventStartTime AS TIME)  AS ST,
       Cast(EventEndTime AS TIME)    AS ET,
       EventTitle,
       EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/        
FROM   Calendar
WHERE  ( PlannedDate >= Getdate() )
       AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
        OR EventEnumDays IS NULL
ORDER  BY EventID,
          PlannedDate
OPTION (maxrecursion 0) 

24

如何在存储过程中使用TempTable?

步骤如下:

创建温度表

-- CREATE TEMP TABLE 
Create Table #MyTempTable (
    EmployeeID int
);

将温度选择数据插入温度表

-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100

SELECT TEMP TABLE(您现在可以使用此选择查询)

Select EmployeeID from #MyTempTable

最后一步拖下桌子

Drop Table #MyTempTable

我希望这将有所帮助。简单明了:)


5
这不能回答问题。OP专门询问如何使用“选择进入”来执行此操作,但此响应没有执行该操作。
DaveInAZ

4
Select      Eventname, 
            count(Eventname) as 'Counts'
INTO        #TEMPTABLE                                                                                
FROM        tblevent
where       Eventname like 'A%'
Group by    Eventname
order by    count(Eventname)

通过使用in子句,可以直接创建表


3
这与现有答案有何不同?
zx8754

1

这是对在执行后创建表的查询的答案的一个略微改动(即,您不必先创建表):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.