包含父/子(组)的MSSQL T-SQL表层次

时间:2014-06-19 09:18:23

标签: sql sql-server tsql foreign-keys

我有一个查询成功列出了与FK级别相关的数据库表层次结构/检查引用的表和列。

这将描述删除/插入数据的顺序。

问题是,在此我想要包括那条路径,即 级别1到'x',但每个组路径都跟随(有些可能有多条路径通过级别)。

任何人都有任何建议,目前使用CTE以递归方式获取关卡。可能使用FK引用的表名?

  ;with    cteTbHierarchy 
      as ( 
           SELECT  distinct
                    1 as LevelID
                  , OBJECT_SCHEMA_NAME(Parent.object_id) as TableOwner
                  , Parent.name as TableName
                  , Parent.object_id as TbObjID
                  , OBJECT_NAME(RefKey.referenced_object_id) as Referenced_Tablename
                  , RefKey.referenced_object_id
                  , RefKey.referenced_column_id
           from     sys.objects Parent
           left outer join sys.foreign_key_columns RefKey
                    On RefKey.parent_object_id = Parent.object_id
                       and RefKey.parent_object_id <> RefKey.referenced_object_id
                       and RefKey.constraint_column_id = 1
           where    RefKey.parent_object_id is null
                    and Parent.type = 'U'
                    and Parent.name <> 'dtproperties'
           UNION ALL
           /* add tables that reference the anchor rows */
           SELECT   H.LevelID + 1
                  , OBJECT_SCHEMA_NAME(Parent.object_id) as TableOwner
                  , OBJECT_NAME(Parent.object_id) as TableName
                  , Parent.object_id as TbObjID
                  , OBJECT_NAME(RefKey.referenced_object_id) as Referenced_Tablename
                  , RefKey.referenced_object_id
                  , RefKey.referenced_column_id
           from     sys.objects Parent
           inner join sys.foreign_key_columns RefKey
                    On RefKey.parent_object_id = Parent.object_id
                       and RefKey.parent_object_id <> RefKey.referenced_object_id
                       and RefKey.constraint_column_id = 1
           inner join cteTbHierarchy H
                    on H.TbObjID = RefKey.referenced_object_id 

           where    Parent.type = 'U'
                    and Parent.name <> 'dtproperties'
         )
select  distinct a.LevelID,
        a.TableOwner,
        a.TableName,
        a.Referenced_Tablename,
        cols.name as Referenced_ColName,
        REPLACE(a.tablename,(LEFT(SUBSTRING(a.TableName, charindex('.',a.TableName), 50),50)),'') as TableArea,
        REPLACE(a.Referenced_Tablename,(LEFT(SUBSTRING(a.Referenced_Tablename, charindex('.',a.Referenced_Tablename), 50),50)),'') as RefTableArea
from    cteTbHierarchy a
left join sys.columns cols
                    on a.referenced_object_id = cols.object_id
                    AND a.referenced_column_id = cols.column_id
order by LevelID asc 
      , TableName;        

0 个答案:

没有答案