SQL Server自定义函数(Scalar-valued Functions)
自定义函数(User-Defined Function)有两种,一种是标量UDF(Scalar-valued Functions)和表值UDF(Table-valued Functions),前者只返回单个数据值,而后者则返回一个表。下面示例是,是属于前者,返回单个值。
代码
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