Add/Drop Foreign Key Values Scripts

These three small scripts come in quite handy when you need to drop and re-create foreign key values for every user table. The scripts run under MS SQL Server 7.0 as well as SQL Server 2000.

The initial script creates the view called sysfkeys and then runs the following scripts in Query Analyzer. The second script will generate a DROP foreign key constraint command against each table for a particular database, while the final script will generate an ADD foreign key constraint command for all user tables for a particular database.

Author: Sushant Saha

/* First create the sysfkey view object */

  CREATE  view sysFKeys as
   select cast(  as varchar(255)) as foreign_key_name
    , r.keycnt
    , cast( as  varchar(255)) as foreign_table
    , cast( as varchar(255)) as  foreign_column_1
    , cast( as varchar(255)) as foreign_column_2
    ,  cast( as varchar(255)) as primary_table
    , cast( as varchar(255))  as primary_column_1
    , cast( as varchar(255)) as  primary_column_2
    from sysobjects f
    inner join sysobjects c on  f.parent_obj =
    inner join sysreferences r on =  r.constid
    inner join sysobjects p on r.rkeyid =
    inner  join syscolumns rc on r.rkeyid = and r.rkey1 = rc.colid
    inner  join syscolumns fc on r.fkeyid = and r.fkey1 = fc.colid
    left join  syscolumns rc2 on r.rkeyid = and r.rkey2 = rc.colid
    left join  syscolumns fc2 on r.fkeyid = and r.fkey2 = fc.colid
    where f.type =  'F'

/* Drop foreignkey constraint from table */

select 'ALTER TABLE ' + foreign_table + ' 
        DROP CONSTRAINT ' + foreign_key_name 
        from sysfkeys order by foreign_table

/* ADD foreignKey constraints to a table */

select 'ALTER TABLE ' + foreign_table + ' ADD CONSTRAINT ' + foreign_key_name + ' 
            FOREIGN KEY (' + foreign_column_1 + ') 
            REFERENCES ' + primary_table + ' (' + primary_column_1 + ')' 
            from sysfkeys order by foreign_table

Disclaimer: We hope that the information on these script pages is valuable to you. Your use of the information contained in these pages, however, is at your sole risk. All information on these pages is provided “as -is”, without any warranty, whether express or implied, of its accuracy, completeness, or fitness for a particular purpose…Disclaimer Continued

Back to Database Journal Home

Get the Free Newsletter!
Subscribe to Cloud Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Cloud Insider for top news, trends & analysis
This email address is invalid.

Latest Articles