在nvarchar字符串中搜索时,SQL Server使用高CPU

Mic*_*art 26 t-sql sql-server

请查看以下示例.它表明在unicode字符串(nvarchar)中搜索几乎是在varchar字符串中搜索的八倍.与隐含转换相提并论.寻找解释.或者更有效地在nvarchar字符串中搜索的方法.

use tempdb
create table test
(
    testid int identity primary key,
    v varchar(36),
    nv nvarchar(36),
    filler char(500)
)
go

set nocount on
set statistics time off
insert test (v, nv)
select CAST (newid() as varchar(36)),
    CAST (newid() as nvarchar(36))
go 1000000

set statistics time on
-- search utf8 string
select COUNT(1) from test where v like '%abcd%' option (maxdop 1)
-- CPU time = 906 ms,  elapsed time = 911 ms.

-- search utf8 string using unicode (uses convert_implicit)
select COUNT(1) from test where v like N'%abcd%' option (maxdop 1)
-- CPU time = 6969 ms,  elapsed time = 6970 ms.

-- search unicode string
select COUNT(1) from test where nv like N'%abcd%' option (maxdop 1)
-- CPU time = 6844 ms,  elapsed time = 6911 ms.
Run Code Online (Sandbox Code Playgroud)

小智 21

寻找解释.

NVarchar是16位,Unicode比较规则比ASCII要复杂得多 - 同时支持的各种语言的特殊字符需要引用更多的处理.

  • 天啊,就是这样!当使用"nv COLLATE Latin1_General_Bin like N'%ABCD%'"时,我得到: - CPU时间= 890毫秒,经过时间= 881毫秒. (5认同)
  • 让我猜一下 - 你是英语演讲者;)与来自德国和法国的一些人交谈,你开始意识到关于口音和特殊字符的部分ODD规则.这只需要时间来解决;)好我们钉了;) (5认同)