获取表格中所有列的信息(特别是pk)

时间:2014-03-13 04:04:37

标签: sql-server sql-server-2008

我尝试获取表格中所有列的信息 有关typename列的示例信息,尤其是有关primary key的信息,但缺少了该信息 我用

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tablename'

它不包含有关primary key的信息。如何得到感谢

4 个答案:

答案 0 :(得分:2)

这样的东西
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'

也许可以试试

SELECT  i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName,
        c.*
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 c   ON  ic.object_id = c.object_id
                        AND ic.column_id = c.column_id
WHERE   i.is_primary_key = 1

答案 1 :(得分:0)

尝试使用sp_help [tablename],它会为您提供主要密钥详情

sp_help [tablename]

sp_help

enter image description here

或者如果您只需要有关主键列的详细信息,请尝试 Mr.Astander 回答

SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'

答案 2 :(得分:0)

您可以检索主键信息并将其加入INFORMATION_SCHEMA.COLUMNS并获取其他列的主键信息。请参阅以下查询。

SELECT c.*,
       CASE WHEN keys.COLUMN_NAME IS NULL 
       THEN 0 
       ELSE 1 
       END AS is_primary  
FROM 
INFORMATION_SCHEMA.COLUMNS c
LEFT OUTER JOIN (
                SELECT col.COLUMN_NAME,col.TABLE_NAME
                FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tab
                INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
                ON Col.Constraint_Name = tab.Constraint_Name
                AND Col.Table_Name = tab.Table_Name
                WHERE Constraint_Type = 'PRIMARY KEY') keys 
ON c.COLUMN_NAME=keys.COLUMN_NAME AND c.TABLE_NAME=keys.TABLE_NAME
ORDER BY c.TABLE_NAME

答案 3 :(得分:0)

尝试:

SELECT TC.TABLE_NAME, CU.CONSTRAINT_NAME, C.DATA_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU
    ON TC.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.COLUMNS C
    ON CU.TABLE_NAME = C.TABLE_NAME AND CU.TABLE_SCHEMA = C.TABLE_SCHEMA AND C.COLUMN_NAME = CU.COLUMN_NAME
WHERE TC.TABLE_NAME = 'tablename' AND CONSTRAINT_TYPE = 'PRIMARY KEY'