Solved

SQL Server Divide columns and handle divide by zero

Posted on 2015-01-25
1
77 Views
Last Modified: 2015-01-25
In SQL Server (2012), I want to divide the values of 2 columns. There are cases where there will be division by zero. I want to do the calculation and handle the division by zero gracefully. A simple example is AB / Hits to get Average. Some AB fields will be zero. Some sort of If statement? If AB = 0, then Average = ".000", else AB/Hits? Thanks for any help.
0
Comment
Question by:dodgerfan
1 Comment
 
LVL 18

Accepted Solution

by:
Simon earned 500 total points
ID: 40569305
Two choices:
1. Use a where clause to exclude the rows with zero denominators.
2. Use a case statement to set the zero denominators to null.

Both demonstrated below...
declare @t1 table (id int,num1 int,num2 int)

insert into @t1
select 1,1,1 union all
select 2,3,2 union all
select 3,0,1 union all
select 4,1,0  union all
select 5,1,null union all
select 6,null,6 

select id,num1,num2,num1/num2 as IntegerDivision,(0.0+num1)/num2 as DecimalDivision 
from @t1 where num2<>0

select id,num1,num2
,cast(num1 as decimal)/case when num2=0 then null else num2 end as DecimalDivision
from @t1

Open in new window

0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question