![]()
CHARINDEX ( expression1 , expression2 [ , start_location ] )
CHARINDEX 仅在 expression1 和 expression2 都为 NULL 时返回 NULL 值
如果在 expression2 内没有找到 expression1,则 CHARINDEX 返回 0。
![]()
三种的不同结果:
(一)select articleid from article where classid=120 and nkey='消费电子'
返回12条记录
(二)select articleid from article where classid=120 and charindex(','+'消费电子'+',',','+nkey+',')>0
返回8条记录
(三)select articleid from article where classid=120 and ','+'消费电子'+','=','+nkey+','
返回10条记录
原因:
1. nkey='消费电子'的情况, 即使 nkey 的值为'消费电子 ', 条件也是成立的.
2. charindex(','+'消费电子'+',',','+nkey+',')>0 这个是包含关系.
3. ','+'消费电子'+','=','+nkey+',' 这个是完全匹配关系.
示例:
DECLARE @t TABLE(id int identity,nkey varchar(10))
INSERT @t SELECT '消费电子'
UNION ALL SELECT '消费电子 '
UNION ALL SELECT ',消费电子,'
select * from @t where nkey='消费电子'
/*-- 结果
id nkey
----------- ----------
1 消费电子
2 消费电子
--*/
select *, ','+'消费电子'+',' from @t where charindex(','+'消费电子'+',',','+nkey+',')>0
/*-- 结果
id nkey
----------- ---------- ----------
1 消费电子 ,消费电子,
3 ,消费电子, ,消费电子,
(2 行受影响)
--*/
select * from @t where ','+'消费电子'+','=','+nkey+','
/*-- 结果
id nkey
----------- ----------
1 消费电子
(1 行受影响)
--*/
![]()
方法A﹕select * from Ta where c1 like 'XYZ%' --索引起作用了
方法B﹕select * from Ta where charIndex('XYZ',c1)>0 --索引沒起作用
这里方法A比方法B要快![]()
示例--找到带有回车的元素项:
select top 10 charindex(CHAR(13),col), * from table_1
where charindex(CHAR(13),col)> 0

浙公网安备 33010602011771号