I have a table called 'scenes'...
id created modified scene_id
------------------------------------------
1 1999-11-31 2000-01-27 ABCD
2 2000-12-31 2001-01-27 EFGH
3 2001-12-31 2002-01-27 IJKL
4 2002-12-31 2003-01-27 MNOP
5 2003-12-31 2004-01-27 QRST
...what I'm trying to do is to duplicate a row (line 2 in this example) at the end of the table n times (4 in this example), but also alter the scene_id to give them unique identifiers. This is a shortened explanation, but the original is a large table with about 50 columns, and I want to split some of the rows into separate parts, to get something like this:
id created modified scene_id
------------------------------------------
1 1999-11-31 2000-01-27 ABCD
2 2000-12-31 2001-01-27 EFGH
3 2001-12-31 2002-01-27 IJKL
4 2002-12-31 2003-01-27 MNOP
5 2003-12-31 2004-01-27 QRST
6 2000-12-31 2001-01-27 EFGH-A
7 2000-12-31 2001-01-27 EFGH-B
8 2000-12-31 2001-01-27 EFGH-C
9 2000-12-31 2001-01-27 EFGH-D
I first saved some of the information in a temporary table called 'variables'
CREATE TEMP TABLE variables (
scene_id TEXT,
num_files INT,
scene_index INT
);
INSERT INTO variables VALUES (
'EFGH',
4,
2
);
SELECT * FROM variables;
scene_id num_files scene_index
------------------------------------
EFGH 4 2
I also stored line 2 in a table called 'dupedScene'
CREATE TEMP TABLE dupedScene AS SELECT * FROM scenes WHERE id = (
SELECT scene_index FROM variables
);
UPDATE dupedScene
SET id = NULL; -- reset id column to trigger auto increment
SELECT * from dupedScene
id created modified scene_id
-------------------------------------------
null 2000-12-31 2001-01-27 EFGH
I then tried various ways to 'loop' INSERT INTO using recursive CTE and JOIN, but I'm struggling to get these things to work together. I got this far, but I keep getting general errors:
WITH RECURSIVE
counter(x) AS (
SELECT 1
UNION ALL
SELECT x + 1
FROM counter
WHERE x < (SELECT num_files FROM variables)
)
INSERT INTO scenes
SELECT * FROM dupedScene
JOIN counter ON x
Any SQL masters that can help?
The query would be
But you have 5 Columns that you try to insert into scenes, but that is easily remeded
see https://www.db-fiddle.com/f/jLbLD5eiRV8gKYc4RrB6o3/0