如何使用SELECT * INTO tempTable FROM CTE sql Query创建Temp表?

时间:2016-07-25 12:05:12

标签: sql sql-server

我有一个MS SQL CTE查询,我想从中创建一个临时表。我不知道该怎么做,因为它给出了一个无效的对象名称错误。

以下是参考的整个查询

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查询创建临时表

1 个答案:

答案 0 :(得分:1)

正确的语法如下所示:

以下是参考的整个查询

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(day, 1, PlannedDate),
           EventType
    from Calendar
    where EventRecurring = 1 and
          dateadd(day, 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
into tempblockeddates
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);

条款的排序非常重要:

  • withselect之前。
  • 查询中间没有分号行终结符。
  • 子查询始终用括号括起来。
  • 最终的where可能不会做你想要的。但是我离开了原来的逻辑。 (我猜你应该有括号。)