sql - Why this CTE expression hangs while temp table runs fine -
i have below sql cte statement found bottleneck performance. while debugging, hangs there (i think table scan) replaced temp table , query runs fine. wanted know if there difference in way cte expression written making statement hang. know ctes have performance hit attached don't think doing special in below query make cte give me such bad performance.
;with contlist (contkey, ckey, createddate, deleteddate, sourceid) ( select contkey, ckey, createddate, deleteddate, sourceid #sometemptable union select list.contkey contkey, fact.ckey ckey, case when fact.createddate > list.createddate fact.createddate else list.createddate end createddate, case when isnull(fact.deleteddate, '9999/01/01') < isnull(list.deleteddate, '9999/01/01') fact.deleteddate else list.deleteddate end deleteddate, fact.datasourcedimkey sourceid contlist list inner join somefact fact on list.ckey = fact.dimkey inner join somedimvw somedim on somedim.somekey = fact.somekey inner join #conttypes conttypes on somedim.sometypeid = conttypes.sometypeid list.deleteddate null )
i replaced above query this:
select contkey, ckey, createddate, deleteddate, sourceid #sometemptable union select list.contkey contkey, fact.ckey ckey, case when fact.createddate > list.createddate fact.createddate else list.createddate end createddate, case when isnull(fact.deleteddate, '9999/01/01') < isnull(list.deleteddate, '9999/01/01') fact.deleteddate else list.deleteddate end deleteddate, fact.datasourcedimkey sourceid #contlist #contlist list inner join somefact fact on list.ckey = fact.dimkey inner join somedimvw somedim on somedim.somekey = fact.somekey inner join #conttypes conttypes on somedim.sometypeid = conttypes.sometypeid list.deleteddate null )
i had (possibly related) situation complex query cte give inconsistent results, depending on parameters supplied.
for example:
first test:
- restart sql server
- run query parameter a, answer in < 1s;
- run query parameter b, answer in < 1s;
second test:
- restart sql server
- run query parameter b, answer in 64s;
- run query parameter a, answer in 64s;
turned out query plan generated "a" efficient, while generated "b" not; since query plans cached, first query run after restart of server controlled performance of queries.
solution force rebuild of statistics database.
Comments
Post a Comment