I have a basic temp table called #rowCreate with a gap in the count column. It copies an existing table called dbo.rowSource.
| parentID | name | count |
|---|---|---|
| 1 | A | 1 |
| 1 | B | 2 |
| 1 | C | 5 |
| 1 | D | 6 |
| 1 | D | 8 |
| 2 | A | 3 |
| 2 | B | 4 |
My goal is to create new rows in the temo table with the previous "valid" record parentID and name, but with the missing gap count. So the new rows would look like this:
| parentID | name | count |
|---|---|---|
| 1 | B | 3 |
| 1 | B | 4 |
| 1 | D | 7 |
My script below works if there's only a 1 count gap. But if the gap is larger, additional rows aren't created. I've tried adjusting nt.count+ 1 BETWEEN tc.FirstMissingId and tc.LastMissingID, but the SELECT is grabbing just the first artificial row to create.
select parentID, name, tc.FirstMissingId
FROM #rowCreate td
LEFT JOIN (select parentID, count+1 as FirstMissingId, nextid - 1 as LastMissingId
from (select t.*, lead(count) over (partition by parentID order by count) as nextid
from dbo.rowSource t
) t
where nextid <> count+1) tc on tc.parentID= td.parentID
LEFT JOIN (select parentID, name, count
from dbo.rowSource) nt on nt.count+ 1 = tc.FirstMissingId
See example with recursive query
output is
And without recursion
there max gap value is 7