I know how to list foreign keys in a given database
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,
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,