Skip to content
Advertisement

Showing null instead of throwing a zero division error by try-catch

Why does this procedure return NULL when count and sum are both 0?

create procedure avgSalaryByPositions
as
begin
begin try  
    declare @sum int
    select @sum=sum(base_salary) from position
    declare @count int
    select @count=count(*) from position
    select @sum/@count
end try
begin catch
    select
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage;  
end catch
end

and does not produce output like this?

create procedure blablabla
as
begin
BEGIN TRY  
    SELECT 1/0;  
END TRY  
BEGIN CATCH  
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage;  
END CATCH;  
end
GO  


exec blablabla

How to change the first procedure to act same as the second one when there is nothing in the table, meaning when sum and count are both 0?

Thanks.

Advertisement

Answer

If there is nothing in the table then you have no rows. In that case, the SUM() returns NULL, not 0.

If you want an error to occur, then replace it with a value:

select @sum = coalesce(sum(base_salary), 0) from position;

The count() will still return 0, so this should generate an error.

Note that avg() would be a more sensible way to do the calculation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement