How to Script Out all The Foreign Keys of a Table
November 17th, 2007 by Andrew Chen
I encountered a problem at work when I was requested to set up one way transactional replication between two databases. The subscribing database already have the tables of the replication and there were many tables in the subscribing database that have foreign keys referencing the replicating tables. So guess what? The initial push of the replication snap shot failed. Because the intial push of the publication snap shot was trying to drop the existing tables and recreate them.
The script has two part. The first part is to generate the drop statements to drop the foreigns keys that referece certain tables. The second part generates the statements to create the foreign keys. The script is writing on SQL server 2005 and it has limitation. It didn’t consider table schema and it doesn’t work on composite foreign keys. If anyone want a SQL 2000 verion or want one that is able to work on composite keys then let me know. I will see if I can help.
select 'ALTER TABLE '+object_name(a.parent_object_id)+
' DROP CONSTRAINT '+ a.name
from sys.foreign_keys a
join sys.foreign_key_columns b
on a.object_id=b.constraint_object_id
join sys.columns c
on b.constraint_column_id = c.column_id
and b.parent_object_id=c.object_id
join sys.columns d
on b.referenced_column_id = d.column_id
and b.referenced_object_id = d.object_id
where object_name(b.referenced_object_id) in
('tablename1','tablename2')
order by c.name
select 'ALTER TABLE '+object_name(a.parent_object_id)+
' ADD CONSTRAINT '+ a.name +
' FOREIGN KEY (' + c.name + ') REFERENCES ' +
object_name(b.referenced_object_id) +
' (' + d.name + ')'
from sys.foreign_keys a
join sys.foreign_key_columns b
on a.object_id=b.constraint_object_id
join sys.columns c
on b.parent_column_id = c.column_id
and a.parent_object_id=c.object_id
join sys.columns d
on b.referenced_column_id = d.column_id
and a.referenced_object_id = d.object_id
where object_name(b.referenced_object_id) in
('tablename1','tablename2')
order by c.name
You should replace tablename with the name of the table you want to script foreign keys


This absolutely is brilliant - many many thanks - it really saved a lot of headache. Bravo!!!
Thanks a bunch! Great script.
This is a great script. Replication is the worst. I recently replicated a database from a publisher to a subscriber, not knowing that the identity values of the subscriber are not incremented. I had to create a script to reseed all the identity values of the subscriber database. Now, I’m seeing my foreign keys didn’t replicate, so I have to reproduce those manually.
Thanks for this!
Thank you very much. You just saved me a lot of time.
I check comments on my blog this morning and and found many positive comments on this post. I am really glad to see it helps.