Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL server: display blank for a zero-valued or NULL-valued integer field

I am able to use this:

select COALESCE(my_integer_field, '') from my_table 

to display zeros for NULL values. How can I not to display anything (no zeros) for NULL or zero values, without resorting to stored procedures?

like image 247
curious1 Avatar asked Apr 19 '16 18:04

curious1


People also ask

How do I display blank instead of zero in SQL?

The only way you can accomplish what you want is to cast/convert your column to a character datatype so you have an empty string.

How do you set a field to blank in SQL?

How to blank out a date field using SQL? "NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement.

IS NULL value same as zero or blank space in SQL?

A NULL value is not same as zero or a blank space. A NULL value is a value which is 'unavailable, unassigned, unknown or not applicable'. Whereas, zero is a number and blank space is a character.

Is blank equal to NULL in SQL?

In particular, null values must be distinguished from blank values: A null database field means that there is no value for a given record. It indicates the absence of a value. A blank database field means that there is a value for a given record, and this value is empty (for a string value) or 0 (for a numeric value).


1 Answers

It looks like a job for presentation layer not DB.

Anyway you could use:

SELECT CASE WHEN my_integer_field = 0 OR my_integer_field IS NULL THEN ''
       ELSE  CAST(my_integer_field AS VARCHAR(10))
       END
FROM my_table;

or using IIF (SQL Server 2012+):

SELECT IIF(my_integer_field = 0 OR my_integer_field IS NULL, 
           '',
           CAST(my_integer_field AS VARCHAR(10)))
FROM my_table;

LiveDemo

Keep in mind that blank (empty string '') will change the datatype of INT to string.


Or even shorter:

SELECT *,COALESCE(NULLIF(CAST(my_integer_field AS VARCHAR(10)) ,'0'), '') AS result
FROM my_table;

LiveDemo2

Output:

╔══════════════════╦════════╗
║ my_integer_field ║ result ║
╠══════════════════╬════════╣
║ NULL             ║        ║
║ 0                ║        ║
║ 1                ║      1 ║
║ 2                ║      2 ║
╚══════════════════╩════════╝
like image 60
Lukasz Szozda Avatar answered Oct 23 '22 11:10

Lukasz Szozda