如何优化此SQL Server系统表查询

时间:2013-04-09 20:41:32

标签: sql sql-server

给定一个具有以下定义的表:

create table consTest(c1 integer null constraint consTest1 check(c1 < 100),
                      c2 integer not null constraint consTestU1 unique,
                      c3 integer not null,
                      c4 integer null,
                      constraint consTest2 check(c2 > c1),
                      constraint consTestU2 unique(c3))

我的应用程序具有以下查询来对系统表执行以描述表中列的约束关系:

SELECT object_schema_name(t17.referencing_id), object_name(t17.referencing_id),
       coalesce(col_name(t17.referenced_id, t17.referenced_minor_id), NULL),
       t16.definition, t16.type
FROM   { oj sys.check_constraints t16 INNER JOIN  sys.sql_expression_dependencies t17 ON ( t17.referencing_id = t16.object_id )  }  
WHERE t17.referenced_id = object_id('consTest') AND
      t16.type = 'C' AND
      object_name(t17.referencing_id) = 'consTest2'
ORDER BY 1 ASC, 2 ASC, 3 ASC

我在执行此查询时看到SQL Server偶尔会出现间歇性崩溃。我的问题不是关于崩溃,而是看看是否有人可以推荐我可以对我的查询进行任何优化。

1 个答案:

答案 0 :(得分:0)

在我的机器上,我得到的估计子树成本为.0100221 vs .0213887与原始查询:

SELECT object_schema_name(t17.referencing_id)
    , object_name(t17.referencing_id)
    , coalesce(col_name(t17.referenced_id, t17.referenced_minor_id), NULL)
    , t16.[definition]
    , t16.[type]
FROM sys.sql_expression_dependencies t17
JOIN sys.check_constraints t16
    ON t17.referencing_id = t16.object_id
    AND t16.[type] = 'C'
    AND object_name(t17.referencing_id) = 'consTest2'
    AND t17.referenced_id = object_id('consTest');
GO