String comparison with varchar variable

I am having trouble understanding why I am getting 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 

I get:

 test1: no test2: yes test3: no 

Why is string comparison performed if varchar is declared without (optional) size?

+4
source share
1 answer

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:

 LEN1 LEN2 1 6 

Therefore, if you do not specify a size for varchar , SQL Server will do it for you. In this case 1. You must always specify the size explicitly.

Bad hit habits: VARCHAR declaration without (length)

+6
source

Source: https://habr.com/ru/post/1486041/


All Articles