Skip to content

Instantly share code, notes, and snippets.

@timabell
Last active September 26, 2015 17:30
Show Gist options
  • Select an option

  • Save timabell/4f2c2bd2098424cb2def to your computer and use it in GitHub Desktop.

Select an option

Save timabell/4f2c2bd2098424cb2def to your computer and use it in GitHub Desktop.
sql server script for finding all the parents of each table, and all the paths to them. http://sqlfiddle.com/#!6/1cf28b/1
-- find all the parents of every table, and all the paths to get to that parent
-- See it in action: http://sqlfiddle.com/#!6/1cf28b/1
with fkCte
as
(
select
cast(pa.name + ' > ' + ch.name as varchar(1000)) hrch,
fk.parent_object_id,
fk.referenced_object_id
from sys.foreign_keys fk
inner join sys.objects pa on pa.object_id = fk.parent_object_id
inner join sys.objects ch on ch.object_id = fk.referenced_object_id
where fk.parent_object_id <> fk.referenced_object_id
-- and ch.name not like 'foo%' -- your exclusions
union all
select
cast(fkCte.hrch + ' > ' + ch.name as varchar(1000)) hrch,
fkCte.parent_object_id,
fk.referenced_object_id
from sys.foreign_keys fk
inner join sys.objects pa on pa.object_id = fk.parent_object_id
inner join sys.objects ch on ch.object_id = fk.referenced_object_id
inner join fkCte on fkCte.referenced_object_id = fk.parent_object_id
where fk.parent_object_id <> fk.referenced_object_id
-- and ch.name not like 'foo%' -- your exclusions
)
select distinct
fkCte.parent_object_id,
pa.name [parent],
fkCte.referenced_object_id,
ch.name [child],
fkCte.hrch
from fkCte
inner join sys.objects pa on pa.object_id = fkCte.parent_object_id
inner join sys.objects ch on ch.object_id = fkCte.referenced_object_id
order by fkCte.hrch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment