在sql sever 2014

时间:2015-10-09 14:58:37

标签: sql sql-server duplicate-removal

我有这个问题,我现在一直试图修复几个小时,基本上我有一个SQL代码打印数据库中的表及其列以及其他一些信息,如下所示: What I get

问题在于我想在第一列中删除重复项,其中显示了表格的名称,但我想离开“#”列。属性在不同的行中,基本上我需要重复项变为空或合并表示同一个表的行的第一列。我知道这是一个广泛的解释,但这就是我想要的样子:wanted result

这是我在sql server 2014下使用的sql代码:

SELECT CAST(t.NAME AS CHAR(12)) AS [Table]
,CAST(c.NAME AS CHAR(20)) AS [Column]
,CAST(d.NAME AS CHAR(9)) AS [Data type]
,CASE 
    WHEN d.NAME IN (
            'char'
            ,'varchar'
            )
        THEN STR(c.max_length, 6, 0)
    ELSE ''
    END AS [Length]
,CASE 
    WHEN d.NAME IN (
            'numeric'
            ,'decimal'
            )
        THEN STR(c.precision, 9, 0)
    ELSE ''
    END AS [Precision]
,CASE 
    WHEN d.NAME IN (
            'numeric'
            ,'decimal'
            )
        THEN STR(c.scale, 5, 0)
    ELSE ''
    END AS [Scale]
,CASE c.is_nullable
    WHEN 0
        THEN 'not null'
    ELSE ''
    END AS [Nullable]
FROM sys.columns AS c
JOIN sys.tables AS t ON c.object_id = t.object_id
JOIN sys.types AS d ON c.system_type_id = d.system_type_id
ORDER BY 1
    ,column_id;

该代码应适用于sql server 2008或更高版本下的任何数据库。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这应该有用;

WITH CTE
AS (
    SELECT ROW_NUMBER() OVER (
            PARTITION BY t.NAME ORDER BY c.NAME
            ) AS ID
        ,CAST(t.NAME AS CHAR(12)) AS [Table]
        ,CAST(c.NAME AS CHAR(20)) AS [Column]
        ,CAST(d.NAME AS CHAR(9)) AS [Data type]
        ,CASE 
            WHEN d.NAME IN (
                    'char'
                    ,'varchar'
                    )
                THEN STR(c.max_length, 6, 0)
            ELSE ''
            END AS [Length]
        ,CASE 
            WHEN d.NAME IN (
                    'numeric'
                    ,'decimal'
                    )
                THEN STR(c.precision, 9, 0)
            ELSE ''
            END AS [Precision]
        ,CASE 
            WHEN d.NAME IN (
                    'numeric'
                    ,'decimal'
                    )
                THEN STR(c.scale, 5, 0)
            ELSE ''
            END AS [Scale]
        ,CASE c.is_nullable
            WHEN 0
                THEN 'not null'
            ELSE ''
            END AS [Nullable]
    FROM sys.columns AS c
    JOIN sys.tables AS t ON c.object_id = t.object_id
    JOIN sys.types AS d ON c.system_type_id = d.system_type_id
    )
SELECT CASE 
        WHEN ct.ID = 1
            THEN ct.[Table]
        ELSE ''
        END AS 'Table'
    ,ct.[Column]
    ,ct.[Data type]
    ,ct.Length
    ,ct.Precision
    ,ct.Scale
    ,ct.Nullable
FROM CTE ct