Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison fails with varchar variable

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?

like image 798
Geoff Avatar asked Jun 13 '13 14:06

Geoff


People also ask

How do I check if two strings are equal in SQL?

We can compare two or more strings using the STRCMP string function, LIKE operator, and Equal operator.

Can we compare string in SQL?

The STRCMP() function compares two strings.

How can I check if a varchar is numeric in SQL Server?

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.

How does string comparison work in SQL?

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'...


1 Answers

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)

like image 134
Tim Schmelter Avatar answered Sep 22 '22 19:09

Tim Schmelter