孔夫子*_*孔夫子 19 sql-server cte t-sql
我通常通过首先构造一个使用正确计划的查询,然后将其复制到类似的查询中来创建计划指南。但是,这有时很棘手,尤其是在查询不完全相同的情况下。从头开始创建计划指南的正确方法是什么?
SQLKiwi 已经提到在 SSIS 中制定计划,有没有一种方法或有用的工具来帮助为 SQL Server 制定一个好的计划?
有问题的具体实例是这个 CTE:SQLFiddle
with cte(guid,other) as (
select newid(),1 union all
select newid(),2 union all
select newid(),3)
select a.guid, a.other, b.guid guidb, b.other otherb
from cte a
cross join cte b
order by a.other, b.other;
Run Code Online (Sandbox Code Playgroud)
有没有任何方法来使结果拿出正好3个不同的guidS和没有更多?我希望将来能够通过包含多次引用的 CTE 类型查询的计划指南来更好地回答问题,以克服一些 SQL Server CTE 怪癖。
Pau*_*ite 14
有什么方法可以使结果产生恰好 3 个不同的 guids 而不是更多?我希望将来能够通过包含多次引用的 CTE 类型查询的计划指南来更好地回答问题,以克服一些 SQL Server CTE 怪癖。
今天不行。在优化之前,非递归公用表表达式 (CTE) 被视为内嵌视图定义,并在它们被引用的每个位置扩展到逻辑查询树中(就像常规视图定义一样)。您查询的逻辑树是:
LogOp_OrderByCOL: Union1007 ASC COL: Union1015 ASC
LogOp_Project COL: Union1006 COL: Union1007 COL: Union1014 COL: Union1015
LogOp_Join
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_ViewAnchor
LogOp_UnionAll
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
LogOp_Project ScaOp_Intrinsic newid, ScaOp_Const
Run Code Online (Sandbox Code Playgroud)
在优化开始之前,请注意两个视图锚点和对内部函数的六个调用newid。尽管如此,许多人认为优化器应该能够识别扩展的子树最初是单个引用对象并相应地简化。还有几个Connect 请求允许显式实现 CTE 或派生表。
更通用的实现会让优化器考虑具体化任意公共表达式以提高性能(CASE使用子查询是今天可能出现问题的另一个示例)。微软研究院早在 2007 年就发表了一篇关于此的论文(PDF),但迄今为止仍未实施。目前,我们仅限于使用表变量和临时表之类的内容进行显式物化。
SQLKiwi 已经提到在 SSIS 中制定计划,有没有一种方法或有用的工具来帮助为 SQL Server 制定一个好的计划?
这只是我的一厢情愿,远远超出了修改计划指南的想法。原则上,编写一个工具来直接操作显示计划 XML 是可能的,但是如果没有使用该工具的特定优化器检测,对于用户来说可能是一种令人沮丧的体验(并且开发人员会想到这一点)。
在这个问题的特定上下文中,这样的工具仍然无法以可由多个消费者使用的方式实现 CTE 内容(在这种情况下将两个输入都提供给交叉连接)。优化器和执行引擎确实支持多消费者假脱机,但仅用于特定目的 - 没有一个可以应用于此特定示例。
While I'm not certain, I have a fairly strong hunch that the RelOps can be followed (Nested Loop, Lazy Spool) even if the query is not exactly the same as the plan - for instance if you added 4 and 5 to the CTE, it still continues to use the same plan (seemingly - tested on SQL Server 2012 RTM Express).
There is a reasonable amount of flexibility here. The broad shape of the XML plan is used to guide the search for a final plan (though many attributes are ignored completely e.g. partitioning type on exchanges) and the normal search rules are considerably relaxed as well. For example, early pruning of alternatives based on cost considerations is disabled, the explicit introduction of cross joins is allowed, and scalar operations are ignored.
有太多细节需要深入,但不能强制过滤器和计算标量的放置,并且形式的谓词column = value被概括,因此包含X = 1或的计划X = @X可以应用于包含X = 502或的查询X = @Y。这种特殊的灵活性可以极大地帮助找到一个自然的强制计划。
在具体的例子中,常量 Union All 总是可以实现为常量扫描;Union All 的输入数量无关紧要。