找出表上的主键和外键

时间:2019-03-30 14:02:23

标签: sql sql-server

我正在使用以下语句来获取sql表的详细信息,并且它可以工作,但是,我似乎无法弄清楚如何找出表的主键字段是谁知道如何实现这一点的?

SELECT c.name Field, 
    t.name Type,
    c.max_length MaxLength,
    c.Precision, 
    c.Scale,
    c.is_nullable,
    c.collation_name,
    '"+ tableName + "' TableName FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE object_id = object_id('" + tableName + "') ORDER BY column_id";

理想情况下,我想要的是上表中的另一个字段,以确定它的主键还是外键是否有办法实现此目标,即使它的yes或no布尔字段也是如此。

我告诉您为什么我要为Sage 200建立到XML平台的反向工程师表并创建正确的xml我需要以上信息

3 个答案:

答案 0 :(得分:2)

在下面进一步尝试查询。请注意:

  • 针对下图所示的(客户->地址)场景进行测试;
  • Microsoft SQL Server版本为 Microsoft SQL Server 2016(RTM-GDR)(KB4019088)-13.0.1742.0(X64)2017年7月5日23:41:17版权所有(c)Microsoft Corporation Developer Edition(64位) )在Windows 10 Home 6.3(Build 17763:);

enter image description here

SELECT
    C.name,
    C.column_id,
    C.object_id,
    C.max_length MaxLength,
    C.Precision, 
    C.Scale,
    C.is_nullable,
    C.collation_name,
    FK.name AS FK_name,
    KC.name AS PK_name
FROM
    sys.columns AS C
LEFT OUTER JOIN
    sys.foreign_key_columns AS FKC ON C.object_id = FKC.parent_object_id AND C.column_id = FKC.parent_column_id
LEFT OUTER JOIN
    sys.foreign_keys AS FK ON  FKC.constraint_object_id = FK.object_id
LEFT OUTER JOIN
    sys.key_constraints AS KC ON  C.object_id = KC.parent_object_id AND C.column_id = KC.unique_index_id
WHERE
    C.object_id = OBJECT_ID('<table name>')
ORDER BY
    C.column_id

---上面“客户”表的输出---

enter image description here

答案 1 :(得分:0)

突出显示表格,然后按ALT + F1类型。向下滚动以获取PK和FK信息

答案 2 :(得分:0)

TABLENAME表示您的表名

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