Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

MSSQL Tip: Get Connected Columns in Related Tables

How to get Foreign Key related columns, having the names of Primary and Foreign tables ? We can use the following MSSQL system tables:


  • sysobjects - for all user objects.
  • sysforeignkeys - for foreign keys.
  • syscolumns - for tables columns.

Build the following query:


SELECT [name] 
  FROM syscolumns 
 WHERE [id] IN (SELECT [id] 
                  FROM sysobjects 
                 WHERE [name] = @foreign_table_name) 
   AND colid IN (SELECT fkey
                   FROM sysforeignkeys SFK 
                   JOIN sysobjects SOF ON SFK.fkeyid = SOF.[id] 
                   JOIN sysobjects SOP ON SFK.rkeyid = SOP.[id]
                  WHERE SOF.[name] = @foreign_table_name
                    AND SOP.[name] = @primary_table_name)

Related Posts:

Monday, January 19, 2004 7:35 AM

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)