How do I handle Error in sql queries?
开发者_如何转开发For sql queries like..
select Quantity_Books/datepart(hour,Rent_Hour) from Rent_Book where (some conditions..)
They will return error when datepart(hour,Rent_Hour) is 0.
If sth like that Happens, I would like to show 0.
I know I should use case when
But I am not really sure how..
Or any other better method?
You'd simply test the value first
select
CASE
WHEN datepart(hour,Rent_Hour) = 0 THEN 0
ELSE Quantity_Books/datepart(hour,Rent_Hour)
END
from
Rent_Book where (some conditions..)
Alternatively, use NULL rules
ISNULL((Quantity_Books / (NULLIF(datepart(hour,Rent_Hour), 0))), 0)
select case when datepart(hour,Rent_Hour)<>0 then Quantity_Books/datepart(hour,Rent_Hour) else 0 end as col ...
精彩评论