x

Understanding PATINDEX query

I am new to SQL server 2000 and 2005. Can anyone tell me why I am getting wrong results while executing the following simple queries

Case 1

SELECT PATINDEX('%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', 'This is a test')

Ans: 1

Case 2

SELECT PATINDEX('%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', 'This is a teŠt')

Ans: 1

Case 3

SELECT PATINDEX('%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', 'his is a teŠt')

Ans: 10 (Deleted "T" from the word "This" and got the Correct answer)

more ▼

asked Nov 09, 2009 at 09:20 AM in Default

SQLserver_novice gravatar image

SQLserver_novice
113 6 6 7

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

You need to specify the strings as unicode strings, and use a collation that is at least case and accent sensitive. I have chosen the most sensitive Latin1 code page available for this query:

SELECT PATINDEX(N'%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', N'This is a test' COLLATE Latin1_General_100_CS_AS_KS_WS)
UNION ALL
SELECT PATINDEX(N'%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', N'This is a teŠt' COLLATE Latin1_General_100_CS_AS_KS_WS)
UNION ALL
SELECT PATINDEX(N'%[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]%', N'his is a teŠt' COLLATE Latin1_General_100_CS_AS_KS_WS)

The results from this query are:

  • 0
  • 13
  • 12

Also, note that your case 3 answer was not correct - it was returning the index of the first 't'.

more ▼

answered Nov 09, 2009 at 09:45 AM

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.4k 61 65 87

Hi Matt, Thank a lot for your Ans. It helped me a lot. It worked fine without COLLATE Latin1_General_100_CS_AS_KS_WS). But With COLLATE Latin1_General_100_CS_AS_KS_WS) i am getting invalid collation error. Please help I am on SQL server 2005.

With regards

Novice
Nov 10, 2009 at 12:19 AM SQLserver_novice
On SQL Server 2005 you would most likely want to use the collation Latin1_General_CS_AS_KS_WS... You can always get a list of collations by using SELECT * FROM ::fn_helpcollations()
Nov 10, 2009 at 12:50 PM Matt Whitfield ♦♦
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x985
x22

asked: Nov 09, 2009 at 09:20 AM

Seen: 2647 times

Last Updated: Nov 09, 2009 at 09:50 AM