Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding new rows (Value, NULL) to a multiple parent child hierarchy

I have a multiple parent child hierarchy consisting of 100k+ records. This is a small subset.

Child Parent
1 2
1 3
2 3

I need to go through each value from the column Parent and check if the same value also exists in the column Child. If it does not, then create a row with (value, NULL). In this example the value 3 does not exist in the Child column so I need it to create a new row with the values (3, NULL).

Child Parent
3 NULL
1 2
1 3
2 3

My code doesn’t return an error but it doesn’t do what I want it to do.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO #table (child, parent)
SELECT (CASE WHEN parent not in (Select child from #table) THEN parent END) as child, Null
FROM #table

I get many new rows with (NULL,NULL) but 0 rows with (value, NULL). It must somehow always skip ahead to the else clause when there are so many new rows with (NULL, NULL) but not sure why.

Using SQL Server Management Studio 17.
Any help is greatly appreciated.

>Solution :

You shouldn’t use case here, but a self left join instead:

INSERT INTO #table (child, parent)
SELECT DISTINCT t1.parent, NULL
FROM #table t1
LEFT JOIN #table t2
    ON t1.parent = t2.child
WHERE t2.child IS NULL

See live demo on Db<>Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading