views:

18

answers:

2

Hey,

I've got a database that doesn't have any foreign keys. I've done some checks and there are a a fair few orphaned records.

Its a pretty large database 500 + tables and I'm looking at the possibility of building the foreign keys back in.

Other than trawling though every single table over time?

Has anybody ever been through this process before and can maybe offer some insights or tips on how to make the process a little easier.

Any help advice appreciated.

A: 

You can work from the largest to smallest tables, or start with the least performant area of the database. Adding keys should help your performance significantly, but you'll have to resolve the orphan rows first. You may need input from the business for that. Expect them to be very confused about what's going on.

Beth
+1  A: 

I assume you mean "doesn't have any foreign key constraints"...if there were no foreign keys, you wouldn't know which records matched at all.

Do the primary and foreign key fields have the same name? As in, the PK table has a "CustomerId" field and the FK table(s) also have a "CustomerId" field? If so, you might be able to query the column properties (perhaps using INFORMATION_SCHEMA, you didn't mention an RDBMS) to figure out some implied relationships. Just query for all the tables that have a field called "CustomerId" that is not a PK and there's a good (but not certain) bet that those tables should have an FK constraint to the Customer table. You could even use the output of the query to generate the DDL to create the constraints.

pjabbott
Thats not a bad idea in most cases the keys do match. And yes I do mean "constraints"
mjmcloug