Sql-server – Verify conditions before creating a constraint

constraintsql server

I've taken over an application database that has been grown from an Access db. As such, the database is in need of some significant refactoring.

The first step that I'm planning is adding a number of Foreign (and at least one Primary) Key constraints. One-by-one, I've been tracking down constraints that have failed when I try to apply them to my development copy, but I plan on adding a significant number of check constraints in the future.

I'd like to keep a running report of problem areas I need to focus on before I can apply any structural changes. Is there a way to verify the constraint criteria on the live system without attempting any schema or other changes?

Best Answer

You can find duplicate PKs:

select pk_col, count(*)
from tab
group by pk_col
having count(*) > 1 -- multiple rows with the same PK exist

Or the actual rows violating the PK:

select * from tab
where pk_col in 
 (
   select pk_col
   from tab
   group by pk_col
   having count(*) > 1 -- multiple rows with the same PK exist
 )

This returns bad FKs:

select * from child_tab as c
where not exists  -- invalid values in FK column
 (
   select * from parent_tab as p
   where c.fk_col = p.pk_col
 )

Now you can fix the bad data before you add the constraint.