开发者

how to change the result to 0 when the result is NULL in sql statement

I have a select statement, sth like..

select col1, col2, col3 from tbl1 where (conditions)

If there is no row,

All I see is..

NULL,NULL,NULL

What I want to get is

0,0,0

I know there is sth like..

select when (condition) then RESULT else 0 end as 'Col1',..... from tbl1

But if i Do that, I have to check condition everyline..

Any better开发者_高级运维 idea??


Try this:

select isnull(col1,0) from tbl1

Another approach, if you intend to get 1 row but didn't get any, you can use the sum coalesce approach:

select coalesce(sum(col1),0) from tbl1

Another one, use WITH so you don't have to re-evaluate rows when filtering don't produce any results:

with result as
(
    select col1, col2, col3 from tbl1 
    where 1 = 0 -- your condition goes here
)
select col1, col2, col3 from result
union
select 0, 0, 0 where not exists(select * from result)


For this type of queries u can use nvl function of sql. Syntax given below..

Nvl( null value colum,0)               

example-- like if one employe dont get the comisition then query wl be..

Select  nvl( cmsn_pct,0) from employee;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜