从CTE结果插入值

时间:2018-06-25 20:42:06

标签: sqlite insert common-table-expression

我有'SchoolYearStartEnd'表

CREATE TABLE SchoolYearStartEnd (
    id               INT  PRIMARY KEY
                          UNIQUE,
    StartDate    DATE,
    EndDate DATE
);

和第二个“ SchoolYearsTeachingDays”表

CREATE TABLE SchoolYearsTeachingDays (
    aDate DATE PRIMARY KEY
                UNIQUE
);

我想用这样的CTE填写日期:

WITH RECURSIVE dates(x) AS (
 SELECT (SELECT StartDate FROM SchoolYearStartEnd)
  UNION ALL
 SELECT DATE(x, '+1 DAYS') FROM dates WHERE x < (SELECT EndDate FROM SchoolYearStartEnd)
 )
 SELECT * FROM dates WHERE CAST(STRFTIME('%w',x) AS INTEGER) > 0
;

我在这里尝试过此代码:

INSERT INTO SchoolYearsTeachingDays (aDate) VALUES (
  WITH RECURSIVE dates(x) AS (
   SELECT (SELECT StartDate FROM SchoolYearStartEnd)
    UNION ALL
   SELECT DATE(x, '+1 DAYS') FROM dates WHERE x < (SELECT EndDate FROM SchoolYearStartEnd)
   )
  SELECT * FROM dates WHERE CAST(STRFTIME('%w',x) AS INTEGER) > 0 -- To exclude Sundays.
 ;
);

但没有成功。我得到这些错误: 错误:“ RECURSIVE”附近:语法错误 sqlite>错误:“)”附近:语法错误

那我在这里想念什么?

最好,朋友

1 个答案:

答案 0 :(得分:1)

从SELECT查询插入时,您must not use VALUES

INSERT INTO SchoolYearsTeachingDays (aDate)
WITH RECURSIVE dates(x) AS (...)
SELECT * FROM dates ...;