编写查询脚本以根据关系连接数据库中的所有表

Scripting a Query to Join All Tables in the database based on relationships

我从各种堆栈溢出问题中提取了一些 SQL,以帮助我提取数据库中的关系。这非常有帮助。 (我把所有这些都放到了 #temptable 中)。

SELECT  fk.name 'FK Name',
        tp.name 'Parent table',
        cp.name, cp.column_id,
        tr.name 'Refrenced table',
        cr.name, cr.column_id
FROM    sys.foreign_keys fk
INNER JOIN  sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN  sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN  sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN  sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN  sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY    tp.name, cp.column_id

这样做是为了创建脚本,在我所有的 table 上为我的所有关系创建 Joins/etc。现在我有点进退两难,我不确定该怎么做。

例如上面的输出显示如下:

它显示名为 Business 的父级 table 具有一系列名为 ID_BsinessCategoryID_BusinessGroup 等的字段。它们链接到名为 BusinessCategoryBusinessGroup

我需要做的是编写一个脚本来为我创建连接

select * 
from Business a
join BusinessCategory b on a.ID_BusinessCategory = b.ID_BusinessCategory 

问题不是我不会写代码,问题是我不知道如何编写数据库脚本来为我编写代码。几乎有 150 table 具有相当数量的关系。

如有任何建议,我们将不胜感激。

这可能是一个很好的起点

DECLARE @join_query NVARCHAR(MAX)

DROP TABLE #temptable

SELECT  fk.name  AS 'FK Name',
        tp.name AS 'Parent table',
        cp.name AS parent_col, 
        cp.column_id AS parent_col_id,
        tr.name AS 'Refrenced table',
        cr.name AS child_col_id, 
        cr.column_id
INTO #temptable
FROM    sys.foreign_keys fk
INNER JOIN  sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN  sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN  sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN  sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id

INNER JOIN  sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY    tp.name, cp.column_id

SELECT @join_query =  CONCAT(
    'SELECT * FROM ', [Parent table],
    STRING_AGG(
        ' JOIN ' + 
        [Refrenced table] + 
        ' ON [' + [Parent table] + '].' + parent_col + ' = [' +
        [Refrenced table] + '].' + child_col_id + ' '
    , '')
)   
FROM #temptable
GROUP BY [Parent table]


EXEC sp_executesql @join_query

上述语句在重新创建临时 table 后所做的是建立一个语句,将这些关系连接到 JOIN 中,按每个父 table 分组。在此之后它执行存储在 @join_query.

中的语句

从这里您可能想要向该语句添加一些存储结果的内容,例如插入到另一个临时文件中 table 或者您甚至可以让它创建一个视图。