问题描述
示例 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
解决方法
我有一个 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,dateadd(dd,1,PlannedDate),EventType from Calendar
where EventRecurring = 1
and dateadd(dd,PlannedDate) <= EventEndDate
)
select EventID,PlannedDate as [EventDates],Cast(PlannedDate As datetime) AS DT,Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET,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 查询中创建一个临时表,我将不胜感激