Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I know how to list foreign keys in a given database
SQL
USE mydatabase;
go
SELECT 
    f.name AS ForeignKey, 
    OBJECT_NAME(f.parent_object_id) AS TableName, 
    COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName, 
    OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName, 
    COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName 
FROM sys.foreign_keys AS f 
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id 
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id;
go

However I want to be able to get the same information from different databases though a t-sql code. I do not want to use "USE database" but I see no other way.

When I add the database name to the above code and run it from database mydatabase,
SQL
SELECT 
    f.name AS ForeignKey, 
    OBJECT_NAME(f.parent_object_id, DB_ID('AdventureWorks2008')) AS TableName, 
    COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName, 
    OBJECT_NAME (f.referenced_object_id, DB_ID('AdventureWorks2008')) AS ReferenceTableName, 
    COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName 
FROM AdventureWorks2008.sys.foreign_keys AS f 
INNER JOIN AdventureWorks2008.sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id 
INNER JOIN AdventureWorks2008.sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
I do not get the column names.

Does anyone have a pointer for getting these?

Thank you,
Posted
Updated 9-Apr-12 7:21am
v2

1 solution

 
Share this answer
 
Comments
Corporal Agarn 9-Apr-12 14:05pm    
Thank you, using the "INFORMATION_SCHEMA" will let me do what I need to do. I think.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900