Hi,I'm having some strange results with T-SQL. I have a table with an ID column. This table has a foreign key reference to itself pointing to the FK_COLUMN.I have loaded some records into a temp table for archiving and I need to find all children, and also load them into the temp table. However these child records may already be in the temp table. I am having these wierd results:If I use the following query I get 0 results,although I know there should be.INSERT INTO @TempTableSELECT a.*FROM DataTable aJOIN @TempTable aa ON a.FK_COLUMN = aa.IDWHERE a.ID NOT IN (SELECT ID FROM @TempTable) -- Exclude records that already exist
If I use the following two query's I get too many results, ie I get duplicate ID's in the temp table.INSERT INTO @TempTableSELECT a.*FROM DataTable aJOIN @TempTable aa ON a.FK_COLUMN = aa.IDWHERE a.ID <> aa.ID -- Exclude records that already existINSERT INTO @TempTableSELECT a.*FROM DataTable aJOIN @TempTable aa ON a.FK_COLUMN = aa.ID AND a.ID <> aa.ID -- Exclude records that already exist
Please can someone spot where I am going wrong.Thanks