Now, this one is interesting...
After 8 years of SQL I'm still learning how to ... ORDER ?!
Check this out:
declare @mytable as table(name varchar(20)) insert into @mytable VALUES('FR-I') insert into @mytable VALUES('FRieR') insert into @mytable VALUES('FR-R') select name from @mytable order by name
The result is incorrectly ordered:
FR-I FRieR FR-R
What ?
What's wrong, why is FRieR befoer FR-R ?
Aha, you figure it out ... It's the unicode of course.
Let' just use good ol' NVARCHAR and problem solved. Right?
Let's see:
declare @mytable as table(name nvarchar(20))
Nop, still incorrectly ordered... Hmmm.... Oh yea its probably some collation mismatch, let's use explicit collation in ORDER clause:
select name from @mytable order by name COLLATE Latin1_General_CI_AS
Still not working ? But why oh why.
BTW
In collation value Latin1_General_CI_AS last chars are VERY important
CI - Case insensitive
AS - Accent sensitive
or
CS - Case sensitive
AI - Accent sensitive
Here is the solution:
select convert(nvarchar,name) as name from @mytable order by name COLLATE Latin1_General_BIN
It's interesting that problem shows face only in quite special case like with char '-'.
Try '+' and no problem.
As always at some point you can't take stuff for granted like ORDER.
"The day you stop learning is the day you die..."
So remmeber : COLLATE Latin1_General_BIN is your best friend :)
No comments:
Post a Comment