Adsense

Thursday, July 3, 2014

Create a list of all FK's with a comma delimited list of columns in SQL Server

Running the query below will create a list of all Foreign Keys and a comma delimited list off all the fields in the relationship.  You'll want to be in the database (i.e. use a "use database" statement).



select t.name as parent_table,
c.name as child_table,
fk.name as foreign_key,
      STUFF(( SELECT  ','+ col.name
            FROM sys.columns col
            inner join sys.foreign_key_columns fkc on fkc.parent_object_id = col.object_id and fkc.parent_column_id = col.column_id
            WHERE col.object_id = t.object_id
            FOR XML PATH('')),1 ,1, '')  as foreign_key_fields
from sys.objects o
inner join sys.objects t on t.object_id = o.parent_object_id
inner join sys.foreign_keys fk on o.object_id = fk.object_id
inner join sys.objects c on fk.referenced_object_id = c.object_id
group by t.name, c.name, fk.name, t.object_id
order by fk.name

No comments:

Post a Comment