Checking if a column is a foreing key with system tables in SQL

With this request, we can see if a column of a given table is a foreign key. If it is the case, we get the parent table and the primary key associated with this column.

Replace MY_COLUMN_NAME and MY_TABLE_NAME with the real table and column values.


SELECT dbo.sysobjects.name as CHILD_TABLE,
dbo.syscolumns.name AS CHILD_COLUMN,
sysobjects_1.name AS PARENT_TABLE,
syscolumns_1.name AS PARENT_COLUMN
FROM dbo.syscolumns syscolumns_1 INNER JOIN
dbo.syscolumns
INNER JOIN
dbo.sysobjects
INNER JOIN
dbo.sysforeignkeys
ON dbo.sysobjects.id = dbo.sysforeignkeys.fkeyid
INNER JOIN
dbo.sysobjects sysobjects_1
ON dbo.sysforeignkeys.rkeyid = sysobjects_1.id
ON dbo.syscolumns.id = dbo.sysforeignkeys.fkeyid AND
dbo.syscolumns.colid = dbo.sysforeignkeys.fkey
ON syscolumns_1.id = dbo.sysforeignkeys.rkeyid AND
syscolumns_1.colid = dbo.sysforeignkeys.rkey
where dbo.sysobjects.name = 'MY_COLUMN_NAME'
and dbo.syscolumns.name = 'MY_TABLE_NAME

Works with SQL Server 2000

No comments: