I'm having trouble with understanding why I get the results below:
declare @myVar1 varchar = 'Friday'
declare @myVar2 varchar(10) = 'Friday'
select
case when @myVar1 = 'Friday' then 'yes' else 'no' end as test1,
case when @myVar2 = 'Friday' then 'yes' else 'no' end as test2,
case when @myVar1 = @myVar2 then 'yes' else 'no' end as test3
What I get is:
test1: no
test2: yes
test3: no
Why does the string comparison fail if the varchar is declared without the (optional) size?
We can compare two or more strings using the STRCMP string function, LIKE operator, and Equal operator.
The STRCMP() function compares two strings.
SQL Server ISNUMERIC() Function The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.
In SQL Server a string comparison is done in alphabetical order. That is "allan" is greater than "alan" because alphabetically "alan" comes before "allan". So, numbers are treated the same when doing string comparison, they are treated in alphabetical order...so, '2' is greater than '12'...
Here's the answer: http://sqlfiddle.com/#!6/d41d8/4737
declare @myVar1 varchar = 'Friday'
declare @myVar2 varchar(10) = 'Friday'
select len(@myVar1)as len1,
len(@myVar2)as len2
Result is:
LEN1 LEN2
1 6
So if you don't specify a size for the varchar
, SQL Server will do it for you. In this case 1. You should always specify the size explicitly.
Bad habits to kick : declaring VARCHAR without (length)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With