We have a requirement where we want to split one row to many rows ( in the same table ) based on some conditions.
Let's suppose we have this table :
| ID | Value |
|---|---|
| 1 | V1 |
| 2 | V2 |
| 3 | V3 |
Requirement is,
- if ID=1, split this row into two more rows where IDs of new rows will be 4 and 5 and the value will be V1 (same as ID = 1 value) only.
- if ID=2, don't split.
- if ID=3, split this row into one more row where ID of the new row will be 6 and value will be V3 (same as ID = 3 value) only.
The final o/p will be :
| ID | Value |
|---|---|
| 1 | V1 |
| 4 | V1 |
| 5 | V1 |
| 2 | V2 |
| 3 | V3 |
| 6 | V3 |
I am looking out for some SQL script/Stored Proc that will help me in achieving the same.
You can generate the rows with a
joinand derived table . . . and then useunion allto bring in the existing rows:If you just want to insert the values, use
insertwith the second query.