最近遇到一个问题,当查询使用到模糊查询时,由于预估返回行数过高,执行计划认为索引查找+Key Lookup的成本过高,因此采用Clustered Index Scan的方式,消耗大量逻辑IO,执行计划较差。
经过测试,发现对于模糊查询,NVARCHAR和VARCHAR的预估返回行数差距很大,因此拿出来供大家一起测试。
首先生成测试数据,分别创建TB101和TB102的表,表上有相同的聚集索引和非聚集索引,表中有100w数据,创建测试数据脚本如下:
DROP TABLE TB101 GO DROP TABLE TB102 GO SELECT CAST(NCHAR(19968+20902*RAND(RID))+NCHAR(19968+20902/2*RAND(RID))+NCHAR(19968+20902/3*RAND(RID)) AS varchar(40)) AS RName ,* INTO TB101 FROM( SELECT ROW_NUMBER()OVER(ORDER BY T1.OBJECT_ID DESC) AS RID,T1.* FROM sys.all_objects T2 CROSS JOIN sys.all_columns T1 ) AS T WHERE T.RID<1000000 GO SELECT * INTO TB102 FROM TB101 GO ALTER TABLE TB102 ALTER COLUMN RName NVARCHAR(40) GO CREATE UNIQUE CLUSTERED INDEX IDX_RID ON TB101(RID) GO CREATE UNIQUE CLUSTERED INDEX IDX_RID ON TB102(RID) GO CREATE INDEX IDX_Name ON TB101(RName) GO CREATE INDEX IDX_Name ON TB102(RName) GO EXEC sp_spaceused ‘TB101‘ EXEC sp_spaceused ‘TB102‘ GO
SELECT * FROM TB101 WHERE RName LIKE ‘你好%‘ SELECT * FROM TB102 WHERE RName LIKE N‘你好%‘
时间: 2024-10-20 23:07:42