Como criar a tabela Temp com a opção * em tentável a partir da consulta CTE

tenho uma consulta CTE MS SQL da qual quero criar uma tabela temporária. Não sei como fazê-lo, pois dá um erro Invalid Object name.

Abaixo está toda a pesquisa para referência

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)

gostaria de um ponto na direcção certa ou se posso criar uma tabela temporária a partir desta consulta CTE

Author: DarkAjax, 2012-07-15

5 answers

Amostra 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

Certifique-se que o quadro é eliminado após a utilização

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End
 161
Author: Balicanta, 2015-11-30 10:15:13

Realmente o formato pode ser bastante simples - às vezes não há necessidade de predefine uma tabela temp-ele será criado a partir dos resultados da seleção.

Select FieldA...FieldN 
into #MyTempTable 
from MyTable
Então, a menos que você queira diferentes tipos ou sejam muito rigorosos na definição, mantenha as coisas simples. Note também que qualquer tabela temporária criada dentro de um procedimento armazenado é automaticamente retirada quando o procedimento armazenado termina a execução. Se o procedimento armazenado a cria uma tabela temporária e as chamadas armazenadas procedimento B, então B será capaz de use a tabela temporária que um criado. No entanto, é geralmente considerado uma boa prática de codificação deixar cair explicitamente todas as tabelas temporárias que criar de qualquer forma.
 95
Author: Rohit, 2015-06-15 06:43:26

O SELECT ... INTO tem de estar na selecção do 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) 
 21
Author: Martin Smith, 2012-07-15 10:54:45

Como utilizar o TempTable no procedimento armazenado?

Aqui estão os passos:

CRIAR UMA TABELA TEMPORÁRIA

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

INSERIR OS DADOS DE SELECÇÃO TEMP NA TABELA TEMP

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

Seleccione a tabela TEMP (poderá agora usar esta opção)

Select EmployeeID from #MyTempTable

PASSO FINAL, LARGAR O QUADRO

Drop Table #MyTempTable
Espero que isto ajude. Simples e claro:)
 13
Author: Manjunath Bilwar, 2017-11-06 20:13:06
Select      Eventname, 
            count(Eventname) as 'Counts'
INTO        #TEMPTABLE                                                                                
FROM        tblevent
where       Eventname like 'A%'
Group by    Eventname
order by    count(Eventname)

Usando a cláusula de entrada, a tabela é criada directamente

 -1
Author: linette J Sebastian, 2018-05-10 09:48:02