且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008 - 获取表约束

更新时间:2022-05-24 23:16:00

您应该使用当前的 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_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for 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