SQL Server 2008- Get table constraints(SQL Server 2008 - 获取表约束)
问题描述
你能帮我构建一个查询来检索所有表中的约束、每个表中的约束计数,并为没有任何约束的表显示 NULL.
Could you help me frame a query that retrieves the constraints in all the tables, the count of constraints in each table, and also display NULL for tables that do NOT have any constraints.
这是我目前所拥有的:
Select SysObjects.[Name] As [Constraint Name] ,
Tab.[Name] as [Table Name],
Col.[Name] As [Column Name]
From SysObjects Inner Join
(Select [Name],[ID] From SysObjects) As Tab
On Tab.[ID] = Sysobjects.[Parent_Obj]
Inner Join sysconstraints On sysconstraints.Constid = Sysobjects.[ID]
Inner Join SysColumns Col On Col.[ColID] = sysconstraints.[ColID] And Col.[ID] = Tab.[ID]
order by [Tab].[Name]
推荐答案
您应该使用当前的 sys 目录视图(如果您使用的是 SQL Server 2005 或更高版本- sysobjects 视图已弃用,应避免使用)- 查看 关于目录视图的大量 MSDN SQL Server 在线文档.
You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.
您可能会对很多视图感兴趣:
There are quite a few views you might be interested in:
sys.default_constraints用于列的默认约束sys.check_constraints用于检查列的约束sys.key_constraints用于键约束(例如主键)sys.foreign_keys用于外键关系
sys.default_constraintsfor default constraints on columnssys.check_constraintsfor check constraints on columnssys.key_constraintsfor key constraints (e.g. primary keys)sys.foreign_keysfor foreign key relations
还有更多 - 看看吧!
您可以查询并加入这些视图以获取所需的信息 - 例如这将列出表、列和在它们上定义的所有默认约束:
You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:
SELECT
TableName = t.Name,
ColumnName = c.Name,
dc.Name,
dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name
这篇关于SQL Server 2008 - 获取表约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 2008 - 获取表约束
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
