我可以在UDF中使用If吗?

时间:2015-09-29 06:27:56

标签: sql-server user-defined-functions

我有一个我应该使用标量UDF的任务,以实现一个业务规则,声明所有商品值都会吸引以下佣金:

•第一季度(1月至3月)10%佣金

•第二季度(4月 - 6月)15%佣金

•第二季度(7月至9月)20%佣金

•第四季度(10月 - 12月)25%佣金

UDF功能应接受要约价值,计算佣金并返还支付给员工的佣金。

我有一张名为Campaign Offer的表格。

Create Table Campaign_Offer
(
       Offer_id         integer identity(1,1) primary key,

       Offer_date           Date        ,

       Customer_id          int ,

       Offer_value          money       ,

       Product_name     varchar(20) ,

       Acceptance_status    varchar(3)  ,

       Employee_ID          char(10)    ,

    Constraint CustomerID foreign key (Customer_id) references marketing_list(Id),
    Constraint EmployeeID foreign key (Employee_ID) references Employee(Employee_id),
    Constraint AcceptanceStatus Check (Acceptance_status in ('yes', 'no'))
)

我试图在这里做到这一点

Create Function OfferCommission (@OfferValue money,@OfferDate date)
Returns money
As
Begin
if @OfferDate between '01/01/2015' and '03/31/2015'
Begin
Return @OfferValue*0.1
End
else
if @OfferDate between '04/01/2015' and '06/31/2015'
Begin
Return @OfferValue*0.15
End
else
if @OfferDate between '07/01/2015' and '09/31/2015'
Begin
Return @OfferValue*0.2
End
else
if @OfferDate between '09/01/2015' and '12/31/2015'
Begin
Return @OfferValue*0.25
End
End

3 个答案:

答案 0 :(得分:4)

您可以使用CASE

Create Function OfferCommission (@OfferValue money,@OfferDate date)
Returns money
As
Begin
 DECLARE @result MONEY;

 SELECT @result = 
   CASE 
    WHEN @OfferDate between '01/01/2015' and '03/31/2015' THEN @OfferValue * 0.1
    WHEN @OfferDate between '04/01/2015' and '06/31/2015' THEN @OfferValue * 0.15
    WHEN @OfferDate between '07/01/2015' and '09/31/2015' THEN @OfferValue * 0.2
    WHEN @OfferDate between '09/01/2015' and '12/31/2015' THEN @OfferValue * 0.25
    ELSE NULL
    END;

  RETURN @result;
END

您可以使用 CHOOSE 来获得 SQL SERVER 2012 + 更短的解决方案。

Create Function OfferCommission (@OfferValue money,@OfferDate date)
Returns money
As
Begin
 RETURN @OfferValue * CHOOSE(DATEPART(QUARTER,@OfferDate), 0.1, 0.15, 0.2, 0.25) 
END

答案 1 :(得分:3)

最好的方法是使用DATEPART函数来确定季度 - 这非常有效:

CREATE FUNCTION OfferCommission (@OfferValue money, @OfferDate date)
RETURNS MONEY
AS
BEGIN
    RETURN CASE  DATEPART(QUARTER,@OfferDate)
        WHEN 1 THEN @OfferValue * 0.1
        WHEN 2 THEN @OfferValue * 0.15
        WHEN 3 THEN @OfferValue * 0.2
        WHEN 4 THEN @OfferValue * 0.25
    END
END
GO

答案 2 :(得分:2)

您可以尝试在以下内容中使用CASE代替IF

CREATE FUNCTION OfferCommission (@OfferValue MONEY, @OfferDate DATE)
RETURNS MONEY
AS
BEGIN
    RETURN CASE WHEN @OfferDate BETWEEN '01/01/2015' AND '03/31/2015' THEN @OfferValue*0.1
                WHEN @OfferDate BETWEEN '04/01/2015' AND '06/31/2015' THEN @OfferValue*0.15
                WHEN @OfferDate BETWEEN '07/01/2015' AND '09/31/2015' THEN @OfferValue*0.2
                WHEN @OfferDate BETWEEN '09/01/2015' AND '12/31/2015' THEN @OfferValue*0.25
            END
END