将公用表表达式的数据保存到表中

时间:2017-03-12 04:55:00

标签: sql sql-server

这是我之前提问的扩展: Auto generating dates based on a table

我得到的分辨率完美无缺

with n as (
      select row_number() over (order by (select null)) - 1 as n
      from master..spt_values
     )
select t.*, dateadd(day, n.n, t.startDate) as thedate
from t join
     n
     on dateadd(day, n.n, t.startDate) <= t.endDate;

但是,我想通过将结果保存到表中来使结果持久化。是否有可能持久化数据?我尝试了 select into statement ,但它无法正常工作

整个陈述是:

select into ABC
(
    with n as (
          select row_number() over (order by (select null)) - 1 as n
          from master..spt_values
         )
    select t.*, dateadd(day, n.n, t.startDate) as thedate
    from t join
         n
         on dateadd(day, n.n, t.startDate) <= t.endDate
)

收到的错误是:

Msg 156, Level 15, State 1, Line 146
Incorrect syntax near the keyword 'into'.
Msg 319, Level 15, State 1, Line 148
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 102, Level 15, State 1, Line 168
Incorrect syntax near ')'.

如何将结果保存到表格中?

2 个答案:

答案 0 :(得分:1)

请注意into ABC

的位置
 ;with n as (
    select row_number() over (order by (select null)) - 1 as n
    from master..spt_values
)
select t.*
     , dateadd(day, n.n, t.startDate) as thedate
 into ABC
 from t join  n      
   on dateadd(day, n.n, t.startDate) <= t.endDate

答案 1 :(得分:0)

with n as (
          select row_number() over (order by (select null)) - 1 as n
          from master..spt_values
         )
with ABC as(
    select t.*, dateadd(day, n.n, t.startDate) as thedate
    from t join
         n
         on dateadd(day, n.n, t.startDate) <= t.endDate
)

现在您可以在另一个查询中使用Abc。