Sql-Server

“NOT Column LIKE 模式”與“Column NOT LIKE 模式”

  • July 26, 2022

這兩個看似等效的表達式之間是否存在邏輯或性能差異?

  1. WHERE NOT [Column] LIKE '%pattern%'
  2. WHERE [Column] NOT LIKE '%pattern%'

…或者兩者都會導致相同的執行計劃和結果?

從邏輯的角度來看,這些是完全相同的。

即使存在NULL也不會影響它,因為如果該列NULL然後[Column] LIKE '%pattern%'評估為UNKNOWN並且NOT UNKNOWN仍然是UNKNOWN並且因此失敗了WHERE.

就實際實現而言,不僅邏輯上相同,而且它們實際上執行相同的程式碼。

仔細檢查XML 查詢計劃會發現以下 XML 在以下情況下[Column] NOT LIKE

<Predicate>
   <ScalarOperator ScalarString="NOT [fiddle_bf98353ecbfa4f60a8c1d988014ffc03].[dbo].[t].[Column] like '%pattern%'">
       <Logical Operation="NOT">
           <ScalarOperator>
               <Intrinsic FunctionName="like">
                   <ScalarOperator>
                       <Identifier>
                           <ColumnReference Database="[fiddle_bf98353ecbfa4f60a8c1d988014ffc03]" Schema="[dbo]" Table="[t]" Column="Column"></ColumnReference>
                       </Identifier>
                   </ScalarOperator>
                   <ScalarOperator>
                       <Const ConstValue="'%pattern%'"></Const>
                   </ScalarOperator>
               </Intrinsic>
           </ScalarOperator>
       </Logical>
   </ScalarOperator>
</Predicate>

在這種情況下NOT [Column] LIKE

<Predicate>
   <ScalarOperator ScalarString="NOT [fiddle_bf98353ecbfa4f60a8c1d988014ffc03].[dbo].[t].[Column] like '%pattern%'">
       <Logical Operation="NOT">
           <ScalarOperator>
               <Intrinsic FunctionName="like">
                   <ScalarOperator>
                       <Identifier>
                           <ColumnReference Database="[fiddle_bf98353ecbfa4f60a8c1d988014ffc03]" Schema="[dbo]" Table="[t]" Column="Column"></ColumnReference>
                       </Identifier>
                   </ScalarOperator>
                   <ScalarOperator>
                       <Const ConstValue="'%pattern%'"></Const>
                   </ScalarOperator>
               </Intrinsic>
           </ScalarOperator>
       </Logical>
   </ScalarOperator>
</Predicate>

換句話說,它們完全相同。

引用自:https://dba.stackexchange.com/questions/314853