Monday, September 17, 2007

IsZero

When you divide the numeric by zero,you'll get the error message.

Message errorServer: Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

You can use this function to solve this problem.

Create functon :

CREATE FUNCTION dbo.iszero(@Value numeric,@Replace int)
RETURNS int
AS
BEGIN
DECLARE @Result int
IF @Value = 0
SET @Result = @Replace
ELSE
SET @Result = @Value
RETURN @Result
END

Test : shows null if function returns null value.

SELECT
Id AS ID,
[IND Volume],
[Volume Grade],
[Volume Grade] / dbo.iszero([IND Volume],null) AS DIV_Result
FROM dbo.LampCustomerAll
WHERE (ASM_Code = 'LM5000') AND ([IND Volume] = 0) OR ([IND Volume] = 2)
ORDER BY Id DESC

Result :

No comments: