您好,我在Sql server中有50个表。
所有表都在加入。
对于前。
国家/地区表
PKCountryID
Name
州表
PKStateID
FKCountryID
Name
城市表
PKCityID
FKStateID
Name
员工表
PKID
FIrstName
LastName
FKCityID
所以我想要所有表格的所有列。为此,我在Fiddle下面写。
这会给我一些结果
COLUMN_NAME
PKEmployeeID
Name
FKCityID
但我想要这样的结果。
COLUMN_NAME
PKEmployeeID
Name
-FKCityID
PKCityID
Name
-FKStateID
PKStateID
Name
-FKCountryID
PKCountryID
Name
PKCityID
Name
-FKStateID
PKStateID
Name
-FKCountryID
PKCountryID
Name
PKStateID
Name
-FKCountryID
PKCountryID
Name
PKCountryID
Name
答案 0 :(得分:0)
您可以尝试递归公用表表达式。类似的东西:
;
WITH cte
AS ( SELECT c.name AS column_name ,
-- t.object_id AS tableid ,
0 AS treelevel
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE t.object_id = 754101727
UNION ALL
SELECT c.name ,-- + ' ' + f.referenced_column_name AS column_name ,
--t.object_id AS tableid ,
treelevel + 1
FROM ( SELECT f.name AS foreign_key_name ,
OBJECT_NAME(f.parent_object_id) AS table_name ,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS constraint_column_name ,
OBJECT_NAME(f.referenced_object_id) AS referenced_object ,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS referenced_column_name ,
is_disabled ,
delete_referential_action_desc ,
update_referential_action_desc ,
f.referenced_object_id AS parent_object_id
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id
) f
JOIN cte ON cte.column_name = f.constraint_column_name
JOIN sys.tables AS t ON t.object_id = f.parent_object_id
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
--IN ORDER TO STOP LOOP AT SPECIFIC LEVEL YOU NEED:
WHERE treelevel < 2
)
SELECT
--IN ORDER TO REMOVE DOUBLINGS ADD DISTINCT
DISTINCT *
FROM cte
ORDER BY treelevel, tableid
您可以在此处找到递归作用:Sql server CTE and recursion example