Subscribe to
Posts
Comments

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.

Sounds an odd replication situation but I need to fullfill it anyway. So I wrote a script to drop the foreign keys that referencing the replicating tables and recreate those foreigns keys after the snap shot has been deliver. There may be other situation where you want to find all the foreign keys that reference certain tables and the following script may help.

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


Related Posts:

  • A Useful Script to Get The Disk Space Used by Every Table
  • T-SQL Query to Get Database Size
  • Join to Parametrized Table Function - Cross Apply and Outer Apply in SQL Server 2005
  • VB Script to Rename All Files in a Folder
  • Shell Script to Start Tomcat on Reboot Using Non-Root User


  • 1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
    Loading ... Loading ...

    RSS feed | Trackback URI

    13 Comments

    Comment by Rocco Subscribed to comments via email
    2008-04-02 08:03:11
    MyAvatars 0.2

    This absolutely is brilliant - many many thanks - it really saved a lot of headache. Bravo!!!

     
    Comment by Keith Subscribed to comments via email
    2008-04-03 07:35:13
    MyAvatars 0.2

    Thanks a bunch! Great script.

     
    Comment by Rich Bateman
    2008-06-06 08:20:31
    MyAvatars 0.2

    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!

     
    Comment by Brandon
    2009-04-22 04:32:07
    MyAvatars 0.2

    Thank you very much. You just saved me a lot of time.

     
    Comment by Andrew Chen
    2009-04-22 08:28:36
    MyAvatars 0.2

    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. :smile:

     
    Comment by Rajesh Subscribed to comments via email
    2009-09-14 21:27:53
    MyAvatars 0.2

    Is there any way to find Missing Foriegn Keys in a SQL SERVER 2005 Database.

     
    Comment by jessica
    2010-01-22 20:09:05
    MyAvatars 0.2

    i got these error messages

    Msg 102, Level 15, State 1, Line 754
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 758
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 770
    Incorrect syntax near ‘.’.

     
    Comment by jessica
    2010-01-22 20:09:45
    MyAvatars 0.2

    i got these errors:

    Msg 102, Level 15, State 1, Line 572
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 579
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 580
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 585
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 592
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 612
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 619
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 655
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 694
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 695
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 705
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 743
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 754
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 758
    Incorrect syntax near ‘.’.
    Msg 102, Level 15, State 1, Line 770
    Incorrect syntax near ‘.’.

     
    Comment by sql admin
    2010-02-14 12:02:44
    MyAvatars 0.2

    Thanks man. That is very useful

     
    Comment by Shrini Viswanathan
    2011-06-14 06:46:50
    MyAvatars 0.2

    Absolutely perfect. Was going to break my head with management studio. Good thing I looked. This took fraction of a second to generate what the scripts.

    Thanks much.

     
    Comment by Vishal
    2011-07-12 14:02:50
    MyAvatars 0.2

    great script. but does not work if there are multiple columns in the foreign key. it returns me 2 drop statement (which is okay) but two create statements - one for each column like this:

    ALTER TABLE TABLE_NAME ADD CONSTRAINT FK__TABLE_NAME__SOMENAME FOREIGN KEY (COLUMN_1) REFERENCES CUSTOMER (COLUMN_1)
    ALTER TABLE TABLE_NAME ADD CONSTRAINT FK__TABLE_NAME__SOMENAME FOREIGN KEY (COLUMN_2) REFERENCES CUSTOMER (COLUMN_2)

    any way to get them all in one statemenet?

     
    Comment by margaret
    2011-12-28 07:34:07
    MyAvatars 0.2

    Thanks! I am building an SSIS package to refresh a test database with production data. Since the process involves truncating the tables and the database has 52 foreign keys, I needed a way to retrieve all the pertinent values for those keys and save them in a table so the package can drop all the foreign keys in the first step of the package and then recreate the foreign keys in the package’s last step. I was close but hadn’t worked out where the column names were. Your post saved me several hours.

     
    Comment by Amir Hussein Samiani Subscribed to comments via email
    2012-02-26 14:23:25
    MyAvatars 0.2

    –Drop and Recreate Foreign Key Constraints

    SET NOCOUNT ON

    DECLARE @table TABLE(
    RowId INT PRIMARY KEY IDENTITY(1, 1),
    ForeignKeyConstraintName NVARCHAR(200),
    ForeignKeyConstraintTableSchema NVARCHAR(200),
    ForeignKeyConstraintTableName NVARCHAR(200),
    ForeignKeyConstraintColumnName NVARCHAR(200),
    PrimaryKeyConstraintName NVARCHAR(200),
    PrimaryKeyConstraintTableSchema NVARCHAR(200),
    PrimaryKeyConstraintTableName NVARCHAR(200),
    PrimaryKeyConstraintColumnName NVARCHAR(200)
    )

    INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
    SELECT
    U.CONSTRAINT_NAME,
    U.TABLE_SCHEMA,
    U.TABLE_NAME,
    U.COLUMN_NAME
    FROM
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
    ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
    WHERE
    C.CONSTRAINT_TYPE = ‘FOREIGN KEY’

    UPDATE @table SET
    PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME
    FROM
    @table T
    INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
    ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME

    UPDATE @table SET
    PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,
    PrimaryKeyConstraintTableName = TABLE_NAME
    FROM @table T
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
    ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME

    UPDATE @table SET
    PrimaryKeyConstraintColumnName = COLUMN_NAME
    FROM @table T
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
    ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME

    –SELECT * FROM @table

    –DROP CONSTRAINT:
    SELECT

    ALTER TABLE [’ + ForeignKeyConstraintTableSchema + ‘].[’ + ForeignKeyConstraintTableName + ‘]
    DROP CONSTRAINT ‘ + ForeignKeyConstraintName + ‘

    GO’
    FROM
    @table

    –ADD CONSTRAINT:
    SELECT

    ALTER TABLE [’ + ForeignKeyConstraintTableSchema + ‘].[’ + ForeignKeyConstraintTableName + ‘]
    ADD CONSTRAINT ‘ + ForeignKeyConstraintName + ‘ FOREIGN KEY(’ + ForeignKeyConstraintColumnName + ‘) REFERENCES [’ + PrimaryKeyConstraintTableSchema + ‘].[’ + PrimaryKeyConstraintTableName + ‘](’ + PrimaryKeyConstraintColumnName + ‘)

    GO’
    FROM
    @table

    GO

     

    Sorry, the comment form is closed at this time.