Why does the case statement return 1 as output in this situation?

1st situation: Why the Case statement returns 1 as output in this situation. First I checked with this query:

DECLARE @VAR INT=0

SELECT CASE
         WHEN @VAR = ' ' THEN 1
         ELSE 0
       END as empty_string

Output :

empty_string
1

After this situation, I tried like this: Second situation: Why does a different value arise when assigning a Local variable?

DECLARE @var1 INT =' '

SELECT @var1 AS empty_assighn

SELECT ' ' AS empty_string

OUTPUT

empty_assighn
0
empty_string
-----------

Then I found that whenever it is assigned, it takes '' (empty string) as a null value. Therefore, I get 1 as output in the 1st situation. But why is this so? What is the reason for this?

Thank you in advance

+4
source share
2 answers

, 0

SELECT CAST(' ' AS INT)

CASE WHEN @VAR = ' ' THEN 1, (INT). , True.

+3

sqlserver ( ) . , msdn link .

, " youardatatype int."

cast convert, " "

:

This will convert without error 

select cast('' as int)
select cast('  ' as int)
select cast(null as int)
select cast(cast( null as datetime) as int)
select cast( cast(0 as decimal) as int)
select cast( cast(1 as bit) as int)
select cast( cast(11 as bit) as int)
select cast( cast(0.0 as decimal) as int)
select cast( cast(0.1 as numeric(18,2)) as int)


This will throw error because it is not have int value
select cast('a' as int)
select cast(' , ' as int)

, Datetime

--As datetime format in sqlserver is yyyy-mm-dd so, if we give this format in string it will convert
select cast('' as datetime)
select cast('20151211' as datetime)  --today date
select cast('2015-12-11' as datetime)
select cast('2015-12-11' as datetime)
select cast('12-11-2015' as datetime)

--this throw error
select cast('2015-24-11' as datetime)
0

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


All Articles