Handling divide by zero

In SQL Server when you divide by 0 you get an error.
image1
0 divided by a number works just fine.
image2
Back to the topic; handling divide by 0 is typically performed using CASE

--declare a table
DECLARE @t TABLE (c1 int, c2 int);
--insert some test data
INSERT INTO @t (c1, c2) VALUES (0,2);
INSERT INTO @t (c1, c2) VALUES (2,0);
--view the table
SELECT * FROM @t;
--handle a divide
SELECT
CASE WHEN c2 = 0 THEN 0 ELSE c1/c2 END AS result
FROM @t;

image3

Leave a Reply