在做分析报表,常常会做到比率计算,由于在MS SQLServer中,特别一点,就是得需要注意分母值问题,所以写了一个自定义函数,日后使用时,只需传入两个参数(分子,分母)即可。
代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_Rate]
(
@Numerator DECIMAL(18,6),
@Denominator DECIMAL(18,6)
)
RETURNS DECIMAL(18,6)
AS
BEGIN
DECLARE @ReturnValue DECIMAL(18,6)
SELECT @ReturnValue=(CASE WHEN @Denominator = 0 THEN NULL WHEN @Denominator IS NULL THEN NULL WHEN @Denominator <> 0 THEN (ISNULL(@Numerator,0) / @Denominator) END)
RETURN @ReturnValue
END
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_Rate]
(
@Numerator DECIMAL(18,6),
@Denominator DECIMAL(18,6)
)
RETURNS DECIMAL(18,6)
AS
BEGIN
DECLARE @ReturnValue DECIMAL(18,6)
SELECT @ReturnValue=(CASE WHEN @Denominator = 0 THEN NULL WHEN @Denominator IS NULL THEN NULL WHEN @Denominator <> 0 THEN (ISNULL(@Numerator,0) / @Denominator) END)
RETURN @ReturnValue
END