如何确定列是否在其表的主键中? (SQL Server)

时间:2008-10-21 15:06:22

标签: sql-server code-generation primary-key data-access-layer

我目前正在使用......

select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns

...确定有关给定数据库中列的信息,以便生成DataAccess图层。

从哪里可以检索有关这些列是否是其表格主键的参与者的信息?

4 个答案:

答案 0 :(得分:33)

这是一种方法(将'keycol'替换为您要搜索的列名称 为):

SELECT K.TABLE_NAME,
K.COLUMN_NAME,
K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND K.COLUMN_NAME = 'keycol';

答案 1 :(得分:6)

同样,以下内容将为您提供有关所有表及其键的信息,而不是有关特定列的信息。这样,您可以确保拥有所有感兴趣的列并知道它们参与了什么。为了查看所有键(主键,外键,唯一键),请注释WHERE子句。

SELECT K.TABLE_NAME, C.CONSTRAINT_TYPE, K.COLUMN_NAME, K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY K.TABLE_NAME, C.CONSTRAINT_TYPE, K.CONSTRAINT_NAME

答案 2 :(得分:3)

根据您的需要,使用INFORMATION_SCHEMA.COLUMNS和INFORMATION_SCHEMA.KEY_COLUMN_USAGE进行完全外部联接。在select语句中,从INFORMATION_SCHEMA.KEY_COLUMN_USAGE添加CONSTRAINT_NAME列,该列将为您提供null或keyname。

select C.Table_Name, C.Column_name, data_type, is_Nullable, U.CONSTRAINT_NAME
from information_Schema.Columns C FULL OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON C.COLUMN_NAME = U.COLUMN_NAME
WHERE C.TABLE_NAME=@TABLENAME

答案 3 :(得分:0)

此查询的返回列具有主键。

SELECT  col.COLUMN_NAME ,
        col.DATA_TYPE ,
        col.CHARACTER_MAXIMUM_LENGTH ln ,
        CAST(ISNULL(j.is_primary, 0) AS BIT) is_primary
FROM    INFORMATION_SCHEMA.COLUMNS col
        LEFT JOIN ( SELECT  K.TABLE_NAME ,
                            K.COLUMN_NAME ,
                            CASE WHEN K.CONSTRAINT_NAME IS NULL THEN 0
                                 WHEN K.CONSTRAINT_NAME IS NOT NULL THEN 1
                            END is_primary
                    FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                            JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
                                                              AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
                                                              AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
                                                              AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
                    WHERE   C.CONSTRAINT_TYPE = 'PRIMARY KEY'
                            AND C.TABLE_NAME = 'tablename'
                  ) j ON col.COLUMN_NAME = j.COLUMN_NAME
WHERE   col.TABLE_NAME = 'tablename'