简体   繁体   中英

Instead of NULL how do I show `0` in result with SELECT statement sql?

I have one stored procedure which is giving me an output (I stored it in a #temp table) and that output I'm passing to another scalar function .

Instead of NULL how do I show 0 in result with SELECT statement sql?

For example stored proc is having select statement like follwing :

SELECT Ename , Eid , Eprice , Ecountry from Etable
Where Ecountry = 'India'

Which is giving me output like

Ename    Eid    Eprice    Ecountry
Ana      12     452       India
Bin      33     NULL      India
Cas      11     NULL      India

Now instead of showing NULL how can I show price as 0 ?

What should be mention in SELECT statement to make NULL as 0 ?

Use coalesce() :

select  coalesce(Eprice, 0) as Eprice

In SQL Server only, you can save two characters with isnull() :

select  isnull(Eprice, 0) as Eprice

Try these three alternatives:

1. ISNULL(MyColumn, 0)

2. SELECT CASE WHEN MyColumn IS NULL THEN 0 ELSE MyColumn END FROM MyTable

3. SELECT COALESCE(MyCoumn, 0) FROM MyTable

There is another way but it is not supported by most of the databases SELECT MyColumn + 0 This might work, but NULL + anything is still NULL in T-SQL.

尝试ISNULL(Eprice, 0)而不是Eprice

You could use this:

SELECT Ename , Eid , ISNULL(Eprice, 0) as Eprice, Ecountry from Etable
Where Ecountry = 'India'

One more difference, if you would get 0 for "Null or Empty" string use coalesce :

select isnull('', 0) as result => ''
select coalesce('', 0) as result => 0

And both return 0 for null value

select isnull(null, 0) as result => 0
select coalesce(null, 0) as result => 0

CASE WHEN price is NULL THEN 0 ELSE price END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM