【问题标题】:Save data of a common table expression into a table将公用表表达式的数据保存到表中
【发布时间】:2017-03-12 13:11:03
【问题描述】:

这是我之前问题的延伸: 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 语句,但没有成功

整个语句是:

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 ')'.

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

【问题讨论】:

  • 请发布您的完整查询插入查询不在此问题中

标签: sql sql-server


【解决方案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

【讨论】:

  • 谢谢约翰!有用!!非常感谢。一个奇怪的问题是 with 前面的分号做什么 (;with) ?没有它我可以逃脱。
  • @user1205746 我包括了 ;以防万一您在 cte 之前有陈述
  • @user1205746 没有提到......很高兴它有帮助:)
【解决方案2】:
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。

【讨论】:

  • 如果你想保存这些结果,你应该使用插入查询
猜你喜欢
  • 1970-01-01
  • 2019-03-23
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
相关资源
最近更新 更多