How to avoid a divide by zero error in a computed column?

332    Asked by bhusha_8629 in SQL Server , Asked on Apr 23, 2021

How do you avoid divide by zero error in the below table? CREATE TABLE [dbo].[TblDivision] ( [Numerator] int NOT NULL, [Denominator] int NOT NULL, [Result] AS (Numerator/ Denominator) ) GO Insert into (Numerator, Denominator) TblDivision values (3,0) GO


Answered by Anne Bell

To solve sql server divide by zero, just add a special case for division by 0: CREATE TABLE [dbo].[TblDivision] ( [Numerator] int NOT NULL, [Denominator] int NOT NULL, [Result] AS case when Denominator=0 then 0 else (Numerator/ Denominator) end );  Hope this helps you solve the SQL server divide by zero queries!



Your Answer

Interviews

Parent Categories