Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to get all foreign key constraints in SQL Server 2000

I need a query for SQL Server 2000 to get a list of all foreign keys.

Particularly all the foreign keys that point to a particular column.

How do I write this query?

like image 846
Kevin Avatar asked May 06 '09 20:05

Kevin


2 Answers

select * from sysobjects
where xtype = 'F'

That should do the trick and be compatible with SQL Server 2000, I hope!

If you additionally need the table and column information in SQL Server 2000, it gets a bit more involved; you need to join the sysforeignkeys and syscolumns catalog views like so:

select
  so.name 'foreign key name',
  OBJECT_NAME(parent_obj) 'table',
  OBJECT_NAME(sf.fkeyid) 'referencing table',
  sc1.name 'referencing column',
  OBJECT_NAME(sf.rkeyid) 'referenced table',
  sc2.name 'referenced column'
from sysobjects so
inner join sysforeignkeys sf on so.id = sf.constid
inner join syscolumns sc1 on sf.fkeyid = sc1.id and sf.fkey = sc1.colid
inner join syscolumns sc2 on sf.rkeyid = sc2.id and sf.fkey = sc2.colid
where so.xtype in ('F','PK')

And if you want to leverage the INFORMATION_SCHEMA views which ARE indeed available in SQL Server 2000, use this query:

SELECT
    rc.CONSTRAINT_NAME,     
    rcu.TABLE_NAME 'Referencing Table', 
    rcu.COLUMN_NAME 'Referencing Column',
    rcu1.TABLE_NAME 'Referenced Table',
    rcu1.COLUMN_NAME 'Referenced Column'
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
INNER JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE rcu 
      ON rc.CONSTRAINT_CATALOG = rcu.CONSTRAINT_CATALOG 
         AND rc.CONSTRAINT_NAME = rcu.CONSTRAINT_NAME
INNER JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE rcu1 
      ON rc.UNIQUE_CONSTRAINT_CATALOG = rcu1.CONSTRAINT_CATALOG 
         AND rc.UNIQUE_CONSTRAINT_NAME = rcu1.CONSTRAINT_NAME

Marc

like image 92
marc_s Avatar answered Oct 14 '22 09:10

marc_s


select * from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS

If you need more information about the key then you can join it to the INFORMATION_SCHEMA.KEY_COLUMN_USAGE view, which contains the columns referenced by the key.

like image 26
David McEwing Avatar answered Oct 14 '22 09:10

David McEwing