I tried to create an average in sql server by dividing two figures. Once I got the error of “Divide by zero error occured”, this is caused by dividing the figure by null value, to handle the error we can use “NULLIF”
DECLARE @ThisMonthAvg decimal(8,2) SET @ThisMonthAvg = @ThisMonthPlayers / NULLIF(@ThisMonthEvents, 0) DECLARE @LastMonthAvg decimal(8,2) SET @LastMonthAvg = @LastMonthPlayers / NULLIF(@LastMonthEvents, 0) DECLARE @ThisYearAvg decimal(8,2) SET @ThisYearAvg = @ThisYearPlayers / NULLIF(@ThisYearEvents, 0) DECLARE @LastYearAvg decimal(8,2) SET @LastYearAvg = @LastYearPlayers / NULLIF(@LastYearEvents, 0)
Leave a Reply