SQL Server 2008:找出表中的主键/外键?

时间:2009-09-03 13:56:41

标签: sql-server

有谁知道我怎么能看到哪些是主要的& amp;表中的外键?

编辑:感谢所有回复。我正在寻找一个SQL查询来做到这一点。现在我正在玩写一个工具,可以列出我所有的DB表并显示列。我还要显示哪些键是主键。

这就是我读出表目录的方式:

const string sqlSelectTable = "SELECT  TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE " +
                                      "FROM INFORMATION_SCHEMA.TABLES " +
                                      "WHERE TABLE_TYPE = 'BASE TABLE' " +
                                      "ORDER BY TABLE_TYPE,TABLE_NAME";

这就是我如何获得关于专栏的信息:

const string sqlSelectTable =
            "SELECT     COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH " +
            "FROM         INFORMATION_SCHEMA.COLUMNS " +
            "WHERE     (TABLE_NAME = @TABLE_NAME) " +
            "ORDER BY ORDINAL_POSITION";

我是否必须创建内部联接,以便查看哪些列是主键?

干杯

5 个答案:

答案 0 :(得分:11)

对于每个表上的主键,您可以使用此查询:

SELECT
    kc.name,
    c.NAME
FROM 
    sys.key_constraints kc
INNER JOIN 
    sys.index_columns ic ON kc.parent_object_id = ic.object_id
INNER JOIN 
    sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE
    kc.type = 'PK'

对于外键,我相信这个查询应该能为您提供必要的信息:

SELECT
    OBJECT_NAME(parent_object_id) 'Parent table',
    c.NAME 'Parent column name',
    OBJECT_NAME(referenced_object_id) 'Referenced table',
    cref.NAME 'Referenced column name'
FROM 
    sys.foreign_key_columns fkc
INNER JOIN 
    sys.columns c 
       ON fkc.parent_column_id = c.column_id 
          AND fkc.parent_object_id = c.object_id
INNER JOIN 
    sys.columns cref 
       ON fkc.referenced_column_id = cref.column_id 
          AND fkc.referenced_object_id = cref.object_id

马克

答案 1 :(得分:4)

答案 2 :(得分:3)

在Management Studio中,展开表格,然后展开“列”项。主键旁边有一个键图标。

要查看外键,请展开“约束”项。

答案 3 :(得分:1)

您可以从:

开始
SELECT 
   Table_Name as [TableName], 
   Column_Name as [ColumnName],
   Constraint_Name as [Constraint], 
   Table_Schema as [Schema]
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
ORDER BY 
   [TableName], 
   [ColumnName]

(您可以按tableName过滤)

答案 4 :(得分:1)

SELECT
OBJECT_NAME(parent_object_id) 'Parent table',
c.NAME 'Parent column name',
OBJECT_NAME(referenced_object_id) 'Referenced table',
cref.NAME 'Referenced column name'
FROM 
sys.foreign_key_columns fkc 
INNER JOIN 
sys.columns c 
   ON fkc.parent_column_id = c.column_id 
      AND fkc.parent_object_id = c.object_id
INNER JOIN 
sys.columns cref 
   ON fkc.referenced_column_id = cref.column_id 
      AND fkc.referenced_object_id = cref.object_id  where OBJECT_NAME(parent_object_id) = 'tablename'

如果要获取所有表的外键关系,请排除where子句,否则请写下您的表名而不是tablename