PATINDEX,通配符和变量

时间:2017-05-05 15:22:40

标签: tsql sql-server-2012 wildcard patindex

如何让PATINDEX对包含%字符的变量进行通配符匹配?

在下文中,我希望PATINDEX返回'%3d'的起始位置:

DECLARE @inputText as VARCHAR(100)
DECLARE @s as Int   
DECLARE @cIn as CHAR(3)

SET @inputText = 'OEi49j3DNxE%3d'
SET @cIn = '%3d'
SET @s = PATINDEX('%' + @cIn +'%', @InputText)

@InputText可以看出,这从第12位开始。

  

OEi49j3DNxE %3d

PATINDEX似乎会将起始位置返回到7,因为它似乎会从%中删除CIn

  

OEi49j的 3D NXE%3D

如何按指定查找%3d,而不是3d

2 个答案:

答案 0 :(得分:2)

您可以使用方括号:

SET @cIn = '[%]3d'
select 
   without_brackets = patindex('%'+'%3d'+'%','OEi49j3DNxE%3d')
 , with_brackets    = patindex('%'+'[%]3d'+'%','OEi49j3DNxE%3d')

rextester演示:http://rextester.com/BVA62284

返回:

+------------------+---------------+
| without_brackets | with_brackets |
+------------------+---------------+
|                7 |            12 |
+------------------+---------------+

答案 1 :(得分:1)

DECLARE @inputText as VARCHAR(100)
DECLARE @s as Int   
DECLARE @cIn as CHAR(3)

SET @inputText = 'OEi49j3DNxE%3d'
SET @cIn = '[%]3d'
SET @s = PATINDEX('%' + @cIn + '%' , @InputText)

select @s

输出:12