查询以获取列元数据,键和索引

时间:2016-02-12 11:15:38

标签: sql-server

如何以下列格式获取表或视图的列元数据

column_name  column_data_type   column_data_length  index          key
-----------------------------------------------------------------------------
column1      int                     4              CLUSTERED      PRIMARYKEY
column2      int                     4              NONCLUSTERED   FOREIGNKEY
column3      varchar                20              NULL           NULL

1 个答案:

答案 0 :(得分:1)

SELECT 
    C.TABLE_SCHEMA+'.'+ C.TABLE_NAME as TableName,
    C.COLUMN_NAME as ColumnName, 
    C.DATA_TYPE as ColumnDataType,
    C.CHARACTER_MAXIMUM_LENGTH as ColumnDataTypeLength, 
    (CASE 
        WHEN K.CONSTRAINT_NAME like 'PK_%' then 'PRIMARYKEY' 
        WHEN K.CONSTRAINT_NAME like 'FK_%' then 'FOREIGNKEY' 
        ELSE NULL 
    END) as [Keys],
    (SELECT     
            i.[type_desc] 
        FROM
            [sys].[indexes] AS i 
        INNER JOIN 
            [sys].[index_columns] AS ic 
            ON i.[object_id] = ic.[object_id] 
            AND i.index_id = ic.index_id
        INNER JOIN 
            [sys].[columns] co
            ON ic.column_id = co.column_id
            AND ic.[object_id] = co.[object_id]
        WHERE 
            i.[object_id] = OBJECT_ID(C.TABLE_SCHEMA+'.'+ C.TABLE_NAME)
            AND co.name=C.COLUMN_NAME
    ) AS [Indexes]
FROM 
    INFORMATION_SCHEMA.COLUMNS C LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
       ON   C.COLUMN_NAME=k.COLUMN_NAME 
            AND C.TABLE_NAME=K.TABLE_NAME
WHERE C.TABLE_SCHEMA+'.'+ C.TABLE_NAME =@tableName 
ORDER BY C.ORDINAL_POSITION ASC