0

why this query is not work correctly?

declare @s nvarchar
set @s = 'abcd'
select patindex('%b%', @s)

it is return zero.

1
  • i accept every usefull question Commented May 25, 2010 at 9:37

2 Answers 2

4

It works if you add a size to your initial declaration of the varchar:

declare @s nvarchar(10) 
set @s = 'abcd' 
select patindex('%b%', @s) 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - beat me to it! Will keep my answer anyway for it's pointer to reference on similar related gotchas
2

It's because if you don't define the size of the NVARCHAR variable, it will be defaulting to size 1. So @s will only ever contain 'a'.

You need to always be careful, to make sure you define the sizes explicitly as different scenarios behave differently as I blogged here.

So, just change

DECLARE @s NVARCHAR

to (e.g.)

DECLARE @s NVARCHAR(20)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.