I would like to be able to clone a record and its descendants in one table. An example of my table might be the following:
Table 1
id | parentid | name --------------------- 1 | 0 | 'Food' 2 | 1 | 'Taste' 3 | 1 | 'Price' 4 | 2 | 'Taste Requirements'
The id column is the primary key and is automatically incremented. The entry "Food" (that is, where id = 1) contains two entries under it, "Taste" and "Price". The entry “Taste” has an entry called “Taste Requirements”. I would like to be able to clone the entry “Food” so that Table 1 looks like this:
Table 1
id | parentid | name --------------------- 1 | 0 | 'Food' 2 | 1 | 'Taste' 3 | 1 | 'Price' 4 | 2 | 'Taste Requirements' 5 | 0 | 'Cookies' 6 | 5 | 'Taste' 7 | 5 | 'Price' 8 | 6 | 'Taste Requirements'
(where "Cookies" is the name of the new category I want to create). I can select all descendants of "Food" using:
with Table1_CTE( id, parentid, name ) as ( select t.id, t.parentid, t.name from Table1 t where t.id = 1 union all select t.id, t.parentid,t. name from Table1 t inner join Table1_CTE as tc on t.parentid = tc.id ) select id, parentid, name from Table1_CTE
and I can only clone the entry "Food" (that is, where id = 1) using:
insert into Table1 ( parentid, name ) select ( parentid, 'Cookies' ) from Table1 where id = 1
but I'm having trouble trying to combine the two queries to clone the descendants of Food. In addition, I try to avoid using stored procedures, triggers, curosrs, etc. Is what I'm trying to make possible? I saw several examples on the Internet, but could not apply them to my requirements.