Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage on Patindex() function

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')
like image 493
Shine Avatar asked Sep 15 '11 06:09

Shine


People also ask

How do you find a space in a string in SQL?

SQL Server SPACE() Function The SPACE() function returns a string of the specified number of space characters.

What is use of Patindex?

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.

How is substring function used?

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.

How do I extract a character from a string in SQL?

The SUBSTRING() function extracts some characters from a string.


3 Answers

select T.Value
from (values
        (charindex('MD', 'FHoisegh MD')),
        (charindex('DO', 'FHoisegh MD'))
     ) as T(Value)
where T.Value > 0
like image 56
Mikael Eriksson Avatar answered Sep 28 '22 08:09

Mikael Eriksson


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.

like image 24
Jeff Ogata Avatar answered Sep 28 '22 09:09

Jeff Ogata


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) )
like image 31
Bogdan Sahlean Avatar answered Sep 28 '22 10:09

Bogdan Sahlean