-- Sample table
CREATE TABLE Foo (
keycol INT PRIMARY KEY,
x INT,
y INT);
INSERT INTO Foo
VALUES(1, 15, 3), (2, 10, 0);
-- Using CASE to check divisor for zero
SELECT keycol,
CASE WHEN y = 0
THEN 0
ELSE x / y
END AS result
FROM Foo;
-- Using NULLIF and COALESCE
SELECT keycol,
COALESCE(x / NULLIF(y, 0), 0) AS result
FROM Foo;
Labels: t-sql programming