sql server - SQL query to find where no primary key exists -


added foreign key relationship table in order had abandon checking data on creation. presume parent(company) objects have been deleted , want find orphaned(division) records. how find row foreign key not exist in primary table?

this thinking struggling clause.

               select  tb_division.divisionname,                             tb_division.divisioncompanyid                   tb_division  left outer join tb_company on tb_division.divisioncompanyid = tb_company.companyid                 (tb_company.companyid = null                             or 'doesn't exist in tb_company') 

any pointers appreciated.

you've got it, need compare using is null predicate:

select  d.divisionname, d.divisioncompanyid  tb_division d left outer join tb_company c    on d.divisioncompanyid = c.companyid  c.companyid null 

or write way, same thing , maybe it's more intuitive:

select  d.divisionname, d.divisioncompanyid  tb_division d not exists (select * tb_company c d.divisioncompanyid = c.companyid); 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -