views:

140

answers:

3

I find this quite odd on Microsoft SQL Server:

SELECT * FROM deliveries WHERE code LIKE '01999195000%'
-- 9 rows returned. Works.

DECLARE @a VARCHAR(10)
SET @a='01999195000%'
SELECT * FROM deliveries WHERE code LIKE @a
-- 0 rows returned? Why not?

SET @a = '01999195000'
SELECT * FROM deliveries WHERE code LIKE @a + '%'
-- 9 rows returned. Works.

What is different between searching for @a which includes the % character, and one that does not but has '%' appended?

If any of you SQL Guru's could share your thoughts, that would be great.

+26  A: 

It's because you've defined @a as a VARCHAR(10), but you've tried putting 12 characters into it...meaning the "%" gets lost from the end

AdaTheDev
Nice! I didn't notice that -
Michael
+1 - Good catch.
Otávio Décio
Actually, I count 12, but the point is still valid.
Joel Coehoorn
Oops, I can't count :) Corrected
AdaTheDev
God, what an idiot I am!!
Simon Hughes
A: 

LIKE is a wildcard character, meaning "anything you like here".

rikh
True, but that isn't the problem given the code provided. I think AdaTheDev has the answer.
JohnFx
Yep, That sounds about right.
rikh
+2  A: 

DECLARE @a VARCHAR(10) is the answer. @a never contains the %.

Mr. Smith
+1 doh!, missed a ton of up votes by just a little....
KM
Haha, thanks! :P
Mr. Smith