[英]SQL need to match the '-' char in patindex() function
I'm trying to use the patindex() function, where I'm matching for the -
character. 我正在尝试使用patindex()函数,在这里我要匹配
-
字符。
select PATINDEX('-', table1.col1 )
from table1
Problem is it always returns 0. 问题是它总是返回0。
The following also didn't work: 以下内容也不起作用:
PATINDEX('\-', table1.col1 )
from table1
PATINDEX('/-', table1.col1 )
from table1
The -
character in a PATINDEX
or LIKE
pattern string outside of a character class has no special meaning and does not need escaping. 本
-
字符在PATINDEX
或LIKE
一个字符类以外的模式字符串没有特殊意义,不需要逃跑。 The problem isn't that -
can't be used to match the character literally, but that you are using PatIndex
instead of CharIndex
and are providing no wildcard characters. 问题不在于
-
不能用于从字面上匹配字符,而是您使用的是PatIndex
而不是CharIndex
并且不提供通配符。 Try this: 尝试这个:
SELECT CharIndex('-', table1.col1 )
FROM Table1;
If you want to match a pattern, it has to use wildcards: 如果要匹配模式,则必须使用通配符:
SELECT PatIndex('%-%', table1.col1 )
FROM Table1;
Even inside a character class, if first or last, the dash also needs no escaping: 即使在字符类内部,即使是第一个或最后一个,连字符也不需要转义:
SELECT PatIndex('%[a-]%', table1.col1 )
FROM Table1;
SELECT PatIndex('%[-a]%', table1.col1 )
FROM Table1;
Both of the above will match the characters a
or -
anywhere in the column. 以上两项将与列中任意位置的字符
a
或-
匹配。 Only if the pattern has characters on either side of the -
inside a character class will it be interpreted as a range. 仅当模式在字符类的
-
两边都有字符时,才会将其解释为范围。
Please make sure to use the '-' as the first or last character within wildcard and it will work. 请确保使用“-”作为通配符中的第一个或最后一个字符,它将起作用。
You can even use the below function to replace any special characters. 您甚至可以使用以下功能替换任何特殊字符。
CREATE Function [dbo].[ReplaceSpecialCharacters](@Temp VarChar(200))
Returns VarChar(200)
AS
Begin
Declare @KeepValues as varchar(200)
Set @KeepValues = '%[-,~,@,#,$,%,&,*,(,),!,?,.,,,+,\,/,?,`,=,;,:,{,},^,_,|]%'
While PatIndex(@KeepValues, @Temp) > 0
SET @Temp =REPLACE(REPLACE(REPLACE( REPLACE (REPLACE(REPLACE( @Temp, SUBSTRING( @Temp, PATINDEX( @KeepValues, @Temp ), 1 ),'') ,' ',''),Char(10),''),char(13),''),' ',''), ' ','')
Return REPLACE (RTRIM(LTRIM(@Temp)),' ','')
End
I am using in my project and it works fine 我在我的项目中使用它,效果很好
I found the answer from another page here. 我从这里的另一页找到了答案。
How to escape underscore character in PATINDEX pattern argument? 如何在PATINDEX模式参数中转义下划线字符?
select PATINDEX('%[-]%', table1.col1 )
from table1
It seems to work, yet I have no idea why. 似乎可行,但我不知道为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.