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.
Saturday, February 21, 2004 1:53 AM