我目前正在尝试通过在 C# 中调用以下 SQL 来检索每个表的表名和主键。这是我迄今为止尝试过的:
SELECT t.TABLE_NAME As 'Table Name',
Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLES t
left outer join INFORMATION_SCHEMA.TABLE_CONSTRAINTS Constraints
on t.TABLE_NAME = Constraints.Table_name
and t.Table_Schema = Constraints.Table_Schema
left outer join INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys
ON Constraints.TABLE_NAME = Keys.TABLE_NAME
and Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME
and Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'
问题是如果表没有主键,我希望结果只包含一个“空”条目。虽然它正在工作,但由于某种原因,结果包含“薪水”表的副本,如下所示。Salary 和Employees 表都有主键,而“Test”表没有:
编辑:我现在已经尝试过了,它似乎有效。这样做有什么缺点吗?
SELECT T.TABLE_NAME As 'Table Name'
, (
Select K1.COLUMN_NAME
From INFORMATION_SCHEMA.TABLE_CONSTRAINTS As C1
Join INFORMATION_SCHEMA.KEY_COLUMN_USAGE As K1
On C1.TABLE_SCHEMA = K1.TABLE_SCHEMA
And C1.TABLE_NAME = K1.TABLE_NAME
And C1.CONSTRAINT_NAME = K1.CONSTRAINT_NAME
Where C1.CONSTRAINT_TYPE = 'PRIMARY KEY'
And T.TABLE_SCHEMA = C1.TABLE_SCHEMA
And T.TABLE_NAME = C1.TABLE_NAME
)As PrimaryKeyColumns
FROM INFORMATION_SCHEMA.TABLES As T