We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

Why does PATINDEX() return incorrect values at various times?

Scott Pletcher
on
Medium Priority
1,072 Views
Last Modified: 2012-06-21
My SQL Server returns 4 as the result of:

SELECT PATINDEX('%[*+-/]%', '|11.0000000000|123-|123456|1234-|5*+')

What am I doing wrong here?  Isn't the first * or + or - or / until much later in the string than position 4??

Other times PATINDEX() will return 0 even when one of the chars is clearly present in the string.

I get the same result from SQL versions 8.00.2055 and 9.00.4035.00 (X64).

What am I specifying wrong?

Or does anyone know of a bug (and fix) for PATINDEX() in SQL Server?
Comment
Watch Question

Commented:
Forward slash '/' is and indicator for an escape character following the forward slash, try without the forward slash in the patindex..

Commented:
Try escaping the forward slash by doubling it and placing it immediately after the '[' character like -

SELECT PATINDEX('%[//*+-]%', '|11.00000000/00|123-|123456|1234-|5*+')
Commented:
Just figured it out, you had the hyphen '-' between '+' and '/', which fooled the parser into thinking +-/ was a range between + and /..

It was actually the hyphen which was causing the issue, leaving it at the end is ensuring that it is used as a literal search character..

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2012

Commented:
Good one.
Scott PletcherSenior DBA
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Author

Commented:
BLESS YOU REB73!!

I overlooked that somehow.  **Thanks sooo much**.  This was driving me crazy :-), since I had the code sooo close to working.
Scott PletcherSenior DBA
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Author

Commented:
Good catch!  Fantastic!!  Thanks.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.