简体   繁体   English

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. 但是当我尝试使用CAST(var AS NVARCHAR)时,查询执行时间超过10分钟,并且在最近的将来似乎没有完成。 But when I change to CAST(var AS VARCHAR) as above, the query finishes in 2-3 seconds. 但是当我如上所述更改为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: 执行计划显示如下: 在此输入图像描述

The nvarchar data type has a higher data type precedence. nvarchar数据类型具有更高的数据类型优先级。 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 CAST,索引列必须首先转换为nvarchar,并且索引不能用于更有效的搜索结果。

The indexed column is already varchar so no column converstion is needed in that case. 索引列已经是varchar,因此在这种情况下不需要列转换。 The index can be used for the more efficient seek data access path in the execution plan. 索引可用于执行计划中更有效的搜索数据访问路径。

This behavior is known as a sargable. 这种行为被称为sargable。 See http://en.wikipedia.org/wiki/Sargable . http://en.wikipedia.org/wiki/Sargable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM