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)
Monday, January 19, 2004 7:35 AM