Vin*_* _S 0 sql-server sql-server-2008-r2
这是我在 SQL Server 2008 R2 中查找主键、外键的查询:
select *
from information_schema.table_constraints
where constraint_type = 'PRIMARY KEY'
Run Code Online (Sandbox Code Playgroud)
知道我需要在我的数据库中选择没有主键表。
谢谢
尝试这个:
SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_NAME 不在( 从 information_schema.table_constraints 选择 TABLE_NAME WHERE constraint_type = '主键' ) AND TABLE_TYPE = '基础表'
编辑:根据@MarkSinkinson 的评论,在 Null 值的情况下,此查询将是错误的 information_schema.table_constraints.table_name
,因此我建议 OP 在评论中添加链接
SELECT OBJECT_SCHEMA_NAME( object_id ) as SchemaName, name AS TableName 从 sys.tables WHERE OBJECTPROPERTY(object_id,'tablehasprimaryKey') = 0 ORDER BY SchemaName, TableName ;
获取没有主键的表列表
了解更多关于这个OBJECTPROPERTY 的信息,这是一个更好的解决方案。