Search code examples
sqlsqliteselectcreate-tablerecursive-query

Error creating a table in SQLite using CREATE TABLE <name> AS SELECT


I am trying to create a dates table that generates EOM dates for a specific date range, but SQLite is throwing an error when creating the table. The current code I have is as follows:

WITH RECURSIVE cnt (
        x
) AS (
    SELECT
            0
    UNION ALL
    SELECT
            x + 1
    FROM
            cnt
    LIMIT (
            SELECT
                    ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1))
)

CREATE TABLE report_dates AS
SELECT
  date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
FROM
  cnt;

However, I am getting the error Query 1 ERROR: near "CREATE": syntax error. Removing the CREATE TABLE report_dates AS line does render the results no problem. What could be driving this?


Solution

  • The cte goes after the create table:

    CREATE TABLE report_dates AS
    WITH RECURSIVE cnt (x) AS (
        SELECT 0
        UNION ALL
        SELECT x + 1
        FROM cnt
        LIMIT (
            SELECT ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1)
        )
    )
    SELECT date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
    FROM cnt;