I have a c_name
column and a name
column, would like get c_name
if it isn't null
or empty string.
I have tested the four SQL queries below. (SQL Server 2012)
All queries will return
name
whenc_name
is a empty string.Only last query will return
name
whenc_name
isnull
.
If null
is not equal to anything, why last statement will return correctly?
select case c_name when '' then name else c_name end as name from employee
select case ltrim(rtrim(c_name)) when '' then name else c_name end as name from employee
select case when ltrim(rtrim(c_name)) = '' then name else c_name end as name from employee
select case when ltrim(rtrim(c_name)) != '' then c_name else name end as name from employee
Update
I test the first comment method, isnull(nullif(c_name, ''), name)
, it can't really return a complete name as expected. ISNULL
truncate your string as checking expression data type. Use COALESCE
instead.
Something about COALESCE
and CASE
: sql - Coalesce vs Case - Stack Overflow
select coalesce(nullif(c_name, ''), name) from employee
More interesting facts about empty string, seems I don't need to care about the how much the space in the string, so the ltrim(rtrim())
seems can be removed. See SQL Server 2008 Empty String vs. Space - Stack Overflow.
Some tests result below, or you can test by yourself in SQL Fiddle
Suppose we use a table like this to test:
c_name | name |
---|---|
NULL | name with c_name null |
name with c_name empty |
select case c_name when '' then name else c_name end as name from employee
select case c_name when '' then name else c_name end as name from employee
select case when c_name = '' then name else c_name end as name from employee
These three statements will return the same result as:
name |
---|
NULL |
name with c_name empty |
select case when c_name != '' then c_name else name end as name from employee
select coalesce(nullif(c_name, ''), name) from employee
Both these statements can return the expected result as:
name |
---|
name with c_name null |
name with c_name empty |
select isnull(nullif(c_name, ''), name) as name from employee
This statement returns a truncated string.
name |
---|
name |
name |