有谁知道我怎么看哪个是主要&表中的外键?
编辑:感谢所有的回复.我正在寻找一个SQL查询来做到这一点.现在我正在玩写一个工具,可以列出所有数据库表并显示列.我还要显示哪些键是主键.
这就是我读出表目录的方式:
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";
我是否必须创建内部联接,以便查看哪些列是主键?
干杯
解决方法
对于每个表上的主键,您可以使用此查询:
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
渣子