How to set a value to true or false by null check in TSQL?
Asked Answered
V

4

6

What is the right syntax to return TRUE if the field is not NULL and to return FALSE if it is NULL in TSQL?

SELECT -- here return TRUE if table.Code IS NOT NULL. And FALSE otherwise
FROM table
Vermillion answered 18/11, 2011 at 12:43 Comment(0)
U
5
 select case 
           when code IS NULL then 'false'
           else 'true'
        end as result
 from the_table
Unbind answered 18/11, 2011 at 12:49 Comment(1)
"return TRUE if table.Code IS NOT NULL"Booth
B
12

There is no true or false in mssql. You can use the datatype bit and consider 1 as true and 0 as false:

SELECT CASE WHEN Code IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END as Result
FROM table 
Beeswing answered 18/11, 2011 at 13:8 Comment(0)
U
5
 select case 
           when code IS NULL then 'false'
           else 'true'
        end as result
 from the_table
Unbind answered 18/11, 2011 at 12:49 Comment(1)
"return TRUE if table.Code IS NOT NULL"Booth
B
3

For fun:

SELECT 
   ISNULL(NULLIF(ISNULL(code,0),code),1) 
FROM table
Booth answered 18/11, 2011 at 13:15 Comment(1)
I agree for fun, poor maintenance team.Proceed
S
1

int's are cast into true, so:

CAST(ISNULL(int, 0) AS bit)

You can use Length(x) if its a string type

Secrete answered 29/12, 2016 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.