我正在使用以下语句来获取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我需要以上信息
答案 0 :(得分:2)
在下面进一步尝试查询。请注意:
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
---上面“客户”表的输出---
答案 1 :(得分:0)
突出显示表格,然后按ALT + F1类型。向下滚动以获取PK和FK信息
答案 2 :(得分:0)
TABLENAME表示您的表名
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TABLENAME'