How to create Temp table with SELECT * INTO tempTable FROM CTE Query

前端 未结 6 1294
执笔经年
执笔经年 2020-12-04 05:39

I have a MS SQL CTE query from which I want to create a temporary table. I am not sure how to do it as it gives an Invalid Object name error.

Below is t

6条回答
  •  时光说笑
    2020-12-04 06:00

    Sample 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
    

    Make sure that the table is deleted after use

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

提交回复
热议问题