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

MSSQL Tip: Get Primary Table in Relationship

How to get Primary Table, having the name of Foreign table in relation ? 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 SOP.[name] 
  FROM sysforeignkeys SFK 
  JOIN sysobjects SOF ON (SFK.fkeyid = SOF.[id]) 
  JOIN sysobjects SOP ON (SFK.rkeyid = SOP.[id]) 
  JOIN syscolumns C ON (C.[id] = SOF.[id] AND C.colid = SFK.fkey)  
 WHERE SOF.[name] = @foreign_table_name 
   AND C.[name] = @foreign_col_name 

Pay attention how sysobjects is used twice in a query.


Related Posts:

Saturday, February 21, 2004 1:53 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 (*)