Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jay16/1b0f0675ee0ece2747cc to your computer and use it in GitHub Desktop.
Save jay16/1b0f0675ee0ece2747cc to your computer and use it in GitHub Desktop.
declare @tableName nvarchar(max)
set @tableName = 'project';
-- 递归遍历出@tableName外键链
with
cte_fk (fk_name, referenced, parent, referenced_item, parent_item, fk_level)
as (
select
fk.name as fk_name
,object_name(fk.referenced_object_id) as referenced
,object_name(fk.parent_object_id) as parent
,'[' + STUFF((
SELECT ',' ,object_name(Col.object_id) + '].[' + col.NAME
FROM sys.foreign_key_columns C
INNER JOIN sys.columns Col ON Col.object_id = c.referenced_object_id AND col.column_id = c.referenced_column_id
WHERE C.constraint_object_id = FK.object_id
FOR XML PATH('')
), 1, 1, '') + ']' referenced_item
,'[' + STUFF((
SELECT ',' ,object_name(Col.object_id) + '].[' + col.NAME
FROM sys.foreign_key_columns C
INNER JOIN sys.columns Col ON Col.object_id = c.parent_object_id AND col.column_id = c.parent_column_id
WHERE C.constraint_object_id = FK.object_id
FOR XML PATH('')
), 1, 1, '') + ']' parent_item
,1 as fk_level
FROM sys.foreign_keys fk
where object_name(referenced_object_id) = @tableName--'project'
union all
select
fk.name as fk_name
,object_name(fk.referenced_object_id) as referenced
,object_name(fk.parent_object_id) as parent
,'[' + STUFF((
SELECT ',' ,object_name(Col.object_id) + '].[' + col.NAME
FROM sys.foreign_key_columns C
INNER JOIN sys.columns Col ON Col.object_id = c.referenced_object_id AND col.column_id = c.referenced_column_id
WHERE C.constraint_object_id = FK.object_id
FOR XML PATH('')
), 1, 1, '') + ']' referenced_item
,'[' + STUFF((
SELECT ',' ,object_name(Col.object_id) + '].[' + col.NAME
FROM sys.foreign_key_columns C
INNER JOIN sys.columns Col ON Col.object_id = c.parent_object_id AND col.column_id = c.parent_column_id
WHERE C.constraint_object_id = FK.object_id
FOR XML PATH('')
), 1, 1, '') + ']' parent_item
,cf.fk_level + 1 as fk_level
FROM sys.foreign_keys fk
inner join cte_fk cf on cf.parent = object_name(fk.referenced_object_id)
)
select * from cte_fk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment