I'm using Maria DB version 10.2.9 on windows 7,
MariaDB > select @@version;
+----------------+
| @@version |
+----------------+
| 10.2.9-MariaDB |
+----------------+
I'm trying to use recursive CTE with INSERT SELECT to create some test Data. For simplicity follows below a single column table to be populated:
CREATE TABLE cte_populated
(
id INT NOT NULL PRIMARY KEY
)
ENGINE = InnoDB;
And the CTE which generates values 1 to 10:
WITH RECURSIVE int_seq AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1
FROM int_seq
WHERE val < 10
)
INSERT cte_populated(id)
SELECT int_seq.val FROM int_seq;
The above generates a syntax error. Note that if the insert line is removed then the 10 rows will appear as expected with values 1 to 10 from the SELECT statement.
Does anyone know restrictions concerning use of CTE in INSERT/SELECT queries, or any workaround?
Update : The following two queries work, both the one from @elenst reply and the one from provided the link in @PM 77 comment:
INSERT cte_populated(id)
WITH RECURSIVE int_seq AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1
FROM int_seq
WHERE val < 10)
SELECT int_seq.val as id FROM int_seq;
The following is an adaptation from the link provided by @PM 77.
INSERT INTO cte_populated
WITH RECURSIVE int_seq(val) AS (
SELECT 1
UNION ALL
SELECT 1 + val FROM int_seq WHERE val < 10)
SELECT * FROM int_seq;
INSERT
.