<>
is … the same as!=
.
但随后一位评论者说道:
It’s true that they are,functionally,the same. However,how the sql optimizer uses them is very different. =/!= are simply evaluated as true/false whereas <> means the engine has to look and see if the value is greater than or less than,meaning more performance overhead. Just something to consider when writing queries that may be expensive.
我确信这是错误的,但为了解决潜在的怀疑论者,我想知道是否有人可以提供权威或规范来源来证明这些运算符不仅在功能上相同,而且在所有方面都相同?
解决方法
这种情况发生在优化器中涉及的任何内容之前.
From 07001
07002
使用调试器和公共符号跟踪代码*,sqllang!DecodeCompOp在寄存器eax **中返回一个值,如下所示:
╔════╦══════╗ ║ Op ║ Code ║ ╠════╬══════╣ ║ < ║ 1 ║ ║ = ║ 2 ║ ║ <= ║ 3 ║ ║ !> ║ 3 ║ ║ > ║ 4 ║ ║ <> ║ 5 ║ ║ != ║ 5 ║ ║ >= ║ 6 ║ ║ !< ║ 6 ║ ╚════╩══════╝
!=和<>两者都返回5,因此在所有后续操作(包括编译和优化)中都无法区分.
虽然次要的是上述观点,但也可以(例如使用未记录的跟踪标志8605)查看传递给优化器的逻辑树,以确认两者都是!=和<>映射到ScaOp_Comp x_cmpNe(不等于标量运算符比较).
例如:
SELECT P.ProductID FROM Production.Product AS P WHERE P.ProductID != 4 OPTION (QUERYTRACEON 3604,QUERYTRACEON 8605); SELECT P.ProductID FROM Production.Product AS P WHERE P.ProductID <> 4 OPTION (QUERYTRACEON 3604,QUERYTRACEON 8605);
两者都产生:
logop_Project QCOL: [P].ProductID logop_Select logop_Get TBL: Production.Product(alias TBL: P) ScaOp_Comp x_cmpNe ScaOp_Identifier QCOL: [P].ProductID ScaOp_Const TI(int,ML=4) XVAR(int,Not Owned,Value=4) AncOp_PrjList
脚注
*我用WinDbg;其他调试器可用.公共符号可通过常用的Microsoft符号服务器获得.有关详细信息,请参阅sql Server客户咨询团队的Looking deeper into SQL Server using Minidumps和Klaus Aschenbrenner的SQL Server Debugging with WinDbg – an Introduction.
**在32位英特尔衍生产品上使用EAX来获取函数的返回值很常见.当然,Win32 ABI就是这样做的,而且我很确定它在旧的MS-DOS时代继承了这种做法,其中AX用于同一目的 – Michael Kjörling