T SQL Identify Orphaned Records
Posted on 2011-02-20
I have asslight problem with a database table and query I could do with some help with.
I have a table 'icomponent' with the following fields (shortened to what is important for now)
'icomponent_id' is an Identity field and the primary key on the table.
'icomponent_parent_id' is a reference back to the icomponent table to allow a heirachy to be defined within the table. It may be null for a top level component or is the ID (icomponent_id) of the parent item.
I already have a FK constraint to ensure that the icomponent_id to icomponent_parent_id link is valid.
My problem is that when displaying these items in the database they are always displayed by their location (ilocation_id) meaning that it is possible and it has happened that two components linked to each other via the icomponent_parent_id field get in different locations which causes the child to not be displayed as its parent is never displayed for the location in which the child has been set. Hope that makes sense so far.
I have tried to create a SQL statement to detect these instances as below:-
select * from icomponent T1
where T1.icomponent_parent_id <> null
and T1.icomponent_parent_id NOT IN
(SELECT icomponent_id FROM icomponent T2 WHERE T1.ilocation_id = T2.ilocation_id)
but I guess I have made an error here - hopefully you can see what I am trying to achieve.
I have two questions :- First how can I modify the query above so that I can find all components whose parent component (if there is one) is NOT in the same location that they are.
Secondly, is it possible to change the foreign key to prevent this from ever happening - if there is how could I re-locate the parent and all of its children in one operation so that I didn't break the FK?