1

除了明显的主/外键约束之外,是否有一种快速的方法来获取数据库中所有约束的列表?

4

1 回答 1

8

假设 SQL Server 2005+(指定SQL Server 的版本总是有用的!):

SELECT 
  [constraint] = name, 
  [object] = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)),
  [definition]
FROM sys.check_constraints
ORDER BY [object], name;

SELECT 
  [constraint] = name,
  [object] = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)),
  [definition]
FROM sys.default_constraints
ORDER BY [object], name;

如果要将它们组合成一个结果集:

SELECT 
  [constraint] = name, 
  type_desc,
  [object] = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)),
  [definition]
FROM sys.check_constraints
UNION ALL
SELECT 
  [constraint] = name,
  type_desc,
  [object] = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
    + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)),
  [definition]
FROM sys.default_constraints
ORDER BY [object], name;
于 2012-05-18T18:55:36.473 回答