IT Misr.com - Egypt's Information Technology Portal

 

search

 Advance Search

Home | Register now. Already a member? Sign In |  

 

spacer

Technical Documents >> Database

Posted:  9 January 2003
Rating:  [N/A]

Add/Drop Foreign Key Values Scripts

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.

RELATED ARTICLES
PHP and Working with Databases (Part III)
Troubleshooting SQL Server Backup/Restore Problems
PHP and Working with Databases (Part II)
SEARCH MAGAZINE

  Type in your search

 Search Now   

MAGAZINE LINKS
News Highlights
Spotlight News
Technical Documents

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.


/* First create the sysfkey view object */

CREATE view sysFKeys as
select cast(f.name as varchar(255)) as foreign_key_name
, r.keycnt
, cast(c.name as varchar(255)) as foreign_table
, cast(fc.name as varchar(255)) as foreign_column_1
, cast(fc2.name as varchar(255)) as foreign_column_2
, cast(p.name as varchar(255)) as primary_table
, cast(rc.name as varchar(255)) as primary_column_1
, cast(rc2.name as varchar(255)) as primary_column_2
from sysobjects f
inner join sysobjects c on f.parent_obj = c.id
inner join sysreferences r on f.id = r.constid
inner join sysobjects p on r.rkeyid = p.id
inner join syscolumns rc on r.rkeyid = rc.id and r.rkey1 = rc.colid
inner join syscolumns fc on r.fkeyid = fc.id and r.fkey1 = fc.colid
left join syscolumns rc2 on r.rkeyid = rc2.id and r.rkey2 = rc.colid
left join syscolumns fc2 on r.fkeyid = fc2.id 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



Reference: www.internet.com
Article ID: 476

 
     
     
 

About Us  | Alliances  | Terms of Use  |  Privacy Statement  |  Contact Us  | Site Info

Mission Statement  | 
© 2002 IT Misr.com.  All rights reserved.