CAST性能中的SQL VARCHAR與NVARCHAR

[英]SQL VARCHAR vs NVARCHAR in CAST performance


I have a query which compares data in two tables:

我有一個查詢比較兩個表中的數據:

SELECT DISTINCT
    MT.Column1,
    MT.Column2,
    MT.Column5,
    MT.Column7,
    MT.Column9
FROM tblMyTable MT
WHERE
    EntryDate >= @StartDate AND EntryDate <= @EndDate AND
    NOT EXISTS (
        SELECT ID FROM tblOtherTable
        WHERE SomeString LIKE 
                'X' + CAST(MT.Column1 AS VARCHAR(16)) +
                'Y' + CAST(MT.Column3 AS VARCHAR(16)) +
                'Z' + CAST(MT.Column4 AS VARCHAR(16)) + '%'
    )

It works OK. But when I'm trying to use CAST(var AS NVARCHAR), the query executes over 10 minutes and doesn't seem to finish in the nearest future. But when I change to CAST(var AS VARCHAR) as above, the query finishes in 2-3 seconds.

它運作正常。但是當我嘗試使用CAST(var AS NVARCHAR)時,查詢執行時間超過10分鍾,並且在最近的將來似乎沒有完成。但是當我如上所述更改為CAST(var AS VARCHAR)時,查詢將在2-3秒內完成。

CASTed columns are defined as:

CASTed列定義為:

  • Column1 int, not null,
  • Column1 int,not null,

  • Column3 varchar(50), not null
  • Column3 varchar(50),不為null

  • Column4 varchar(9),not null
  • Column4 varchar(9),不為null

but in fact all contain ONLY numbers, 9-15 digits in length

但實際上所有都只包含數字,長度為9-15位

I wonder what could be the reason for such performance loss?

我想知道這種性能損失的原因是什么?

UPDATE:

Execution plan shows the folowing: enter image description here

執行計划顯示如下:

1 个解决方案

#1


6  

The nvarchar data type has a higher data type precedence. So with the nvarchar CAST, the indexed column must first be converted to nvarchar and the index cannot be used for the more efficient seek as a result.

nvarchar數據類型具有更高的數據類型優先級。因此,對於nvarchar CAST,索引列必須首先轉換為nvarchar,因此索引不能用於更有效的搜索。

The indexed column is already varchar so no column converstion is needed in that case. The index can be used for the more efficient seek data access path in the execution plan.

索引列已經是varchar,因此在這種情況下不需要列轉換。索引可用於執行計划中更有效的搜索數據訪問路徑。

This behavior is known as a sargable. See http://en.wikipedia.org/wiki/Sargable.

這種行為被稱為sargable。見http://en.wikipedia.org/wiki/Sargable。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/10/03/730115c6045e9c68aeeb65de41df9ad4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com