构建包含来自不同表的两个联接的CTE

时间:2017-02-03 08:58:34

标签: sql-server sql-server-2014 common-table-expression

我正在尝试构建一个CTE,用于显示父子关系以及表名和描述(如下图所示)。我有一个查询选择事实表和一个选择所有表维度和事实表以及相关列等单独但我似乎无法在构建CTE时将它们合二为一,无论我遵循哪个指南。关于如何做到这一点的任何想法?我希望它看起来如下,我使用的是AdventureWorksDw2012。

   Parent |  Table name | Column name | Description
|___________________________________________________
|FactTbl1 |  DimResel  |   Phone     |  Phone nr to empl
|            DimProd   |   ListPrice |  Rec. price to cust.
|FactTbl2 |  DimCurr   |   CurrencyN.|  Name of currency
|

编辑:根据@ Tyron78

的要求添加了查询

这是我试图合并的两个问题:

   SELECT DISTINCT tbl.name
    FROM sys.tables AS tbl
    LEFT JOIN sys.foreign_key_columns AS fkey
    ON tbl.object_id = fKey.parent_object_id
    LEFT JOIN sys.foreign_key_columns AS rKey 
    ON tbl.object_id = rKey.referenced_object_id
    WHERE rKey.referenced_object_id IS NULL


    SELECT DISTINCT
    t.TABLE_SCHEMA AS [Parent], 
    t.TABLE_NAME AS [Object],
    t.COLUMN_NAME AS [Type], 
    cd.value AS [Description]
    FROM INFORMATION_SCHEMA.COLUMNS AS t
    INNER JOIN syscolumns c
    ON c.name = t.COLUMN_NAME
    LEFT OUTER JOIN sys.extended_properties cd
    ON cd.major_id = c.id
    AND cd.minor_id = c.colid
    AND cd.name = 'MS_Description'
    WHERE t.TABLE_NAME in ('MyTables')

这是我试过的CTE-Query但没有工作

WITH Parents
AS ( SELECT DISTINCT tbl.name
FROM sys.tables AS tbl
LEFT JOIN sys.foreign_key_columns AS fkey
    ON tbl.object_id = fKey.parent_object_id
    LEFT JOIN sys.foreign_key_columns AS rKey 
    ON tbl.object_id = rKey.referenced_object_id
    WHERE rKey.referenced_object_id IS NULL
UNION ALL
    SELECT DISTINCT
    t.TABLE_SCHEMA AS [Parent], 
    t.TABLE_NAME AS [Object],
    t.COLUMN_NAME AS [Type], 
    cd.value AS [Description]
FROM INFORMATION_SCHEMA.COLUMNS AS t
INNER JOIN syscolumns c
    ON c.name = t.COLUMN_NAME
    LEFT OUTER JOIN sys.extended_properties cd
    ON cd.major_id = c.id
    AND cd.minor_id = c.colid
    AND cd.name = 'MS_Description'
    WHERE t.TABLE_NAME in ('MyTables'))
SELECT *
FROM Parents

0 个答案:

没有答案