pointers, solutions and scripts for the SQL DBAnot intended to replace common sense

2/18/2013

Script Out Foreign Keys With Multiple Keys

It's easy enough to use sys.foreign_keys and sys.foreign_key_columns to identify foreign keys. But what if you want to script out your foreign keys (and only your foreign keys)... that have compound primary keys?

Here's how I recently did this. It actually turned out to be more complicated than I thought, certainly more complicated that your standard throw-strings-together-based-on-system-tables. This is because we need to build a recurse of the multi-key values that are both referenced and referencing in foreign keys.