SQL Server 2005+ - 获取所有默认值并检查约束

时间:2013-11-27 19:51:22

标签: sql sql-server sql-server-2008

我有以下查询(今天戴上我的dba帽:))我想知道是否有人知道更好的方法来获得没有Union All的默认和检查约束。这肯定会使where子句更容易,更有效。

SELECT 
    t.Name AS [TableName],
    SCHEMA_NAME(t.schema_id) AS [SchemaName], 
    c.Name AS [ColumnName],
    dc.Name AS ConstraintName,
    'DEFAULT' AS ConstraintType,
    dc.definition AS ConstraintDef
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
UNION ALL
SELECT 
    t.Name AS [TableName],
    SCHEMA_NAME(t.schema_id) AS [SchemaName], 
    c.Name AS [ColumnName],
    cc.Name AS ConstraintName,
    'CHECK' AS ConstraintType,
    cc.definition AS ConstraintDef
FROM sys.tables t
INNER JOIN sys.check_constraints cc ON t.object_id = cc.parent_object_id
INNER JOIN sys.columns c ON cc.parent_object_id = c.object_id AND c.column_id = cc.parent_column_id

请注意,这需要适用于SQL Server 2005+以及azure。当我需要动态添加where子句以限制结果时,当前脚本可以正常工作但不能有效工作。

1 个答案:

答案 0 :(得分:4)

您可以减少JOIN的总量,例如:

with constraints as (
    select parent_object_id, parent_column_id, name, definition, 
           'DEFAULT' [ConstraintType] 
    from sys.default_constraints
    union all
    select parent_object_id, parent_column_id, name, definition, 'CHECK'
    from sys.check_constraints
)

SELECT 
    t.Name AS [TableName],
    SCHEMA_NAME(t.schema_id) AS [SchemaName], 
    c.Name AS [ColumnName],
    dc.Name AS ConstraintName,
    dc.ConstraintType,
    dc.definition AS ConstraintDef
FROM sys.tables t
INNER JOIN 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

或者您可以使用其他方法(使用sys.sysconstraintssys.objects

SELECT 
    t.Name AS [TableName],
    SCHEMA_NAME(t.schema_id) AS [SchemaName], 
    c.Name AS [ColumnName],
    dc.Name AS ConstraintName,
    dc.ConstraintType,
    dc.definition AS ConstraintDef
FROM sys.tables t
INNER JOIN (
    SELECT object_definition(o.object_id) [definition], OBJECT_NAME(o.OBJECT_ID) [Name],
    o.parent_object_id, o.type_desc [ConstraintType], c.colid [parent_column_id]
    FROM sys.objects o
    join sys.sysconstraints c on o.object_id = c.constid
    WHERE type_desc in ('DEFAULT_CONSTRAINT', 'CHECK_CONSTRAINT')
 ) 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