I am using patindex
for pattern search of "MD" or "DO". The below statement returns 3
.
Am I using it in the wrong way or is there another way of checking condition?
select PATINDEX ('%[MD,DO]%','FHoisegh MD')
SQL Server SPACE() Function The SPACE() function returns a string of the specified number of space characters.
The PATINDEX() function in the SQL server is used to return the starting index of the first occurrence of a pattern in a string or a specified expression. It returns zero if the pattern is not found. It returns NULL if either pattern or expression is NULL.
The SUBSTRING() function extracts a substring starting from a position in an input string with a given length. In the case of substring, you need an input string and need to mention the starting point and the total length of the string. Input : String, start, length output : substring.
The SUBSTRING() function extracts some characters from a string.
select T.Value
from (values
(charindex('MD', 'FHoisegh MD')),
(charindex('DO', 'FHoisegh MD'))
) as T(Value)
where T.Value > 0
select PATINDEX ('%[MD][DO]%','FHoisegh MD') -- returns 10
As you have it in your question, it is looking for any of the 5 characters between the square brackets, and finds 'o' at position 3. For example,
select PATINDEX ('%[MD,DO]%','F,Hoisegh MD') -- returns 2
As @Filip De Vos pointed out, '%[MD][DO]%'
will also match MO
. The only way I can think of to handle this would be to subtract out the index for MO
:
select PATINDEX ('%[MD][DO]%','FHoisegh MO') - PATINDEX('%MO%', 'FHoisegh MO') -- returns 0
If MD
and DO
are the only terms you'll be searching for, this might suffice. For anything else, I'd say look for other ways to do it.
With a combination of PATINDEX/CHARINDEX, NULLIF & ISNULL functions you can get the desired result:
DECLARE @text VARCHAR(100) = 'FHoisegh MXD';
SELECT ISNULL( NULLIF(PATINDEX('%MD%',@text),0), PATINDEX('%DO%',@text) )
If you search for three or more values (ex. DO / RE / MI) instead of ISNULL function can be used COALESCE function:
DECLARE @text VARCHAR(100) = 'abcMODOKO';
SELECT COALESCE( NULLIF(PATINDEX('%DO%',@text),0), NULLIF(PATINDEX('%RE%',@text),0), PATINDEX('%MI%',@text) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With