我可以在 UDF 中使用 If 吗?

Can I use If in a UDF?

我有一个任务,我应该使用标量 UDF 来实施一个业务规则,该规则规定所有报价价值都会吸引以下佣金:

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

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

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

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

UDF 函数应接受报价值、计算佣金和return要支付给员工的佣金。

我有一个名为 Campaign Offer 的 table。

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

您可以使用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

您可以使用 CHOOSESQL SERVER 2012+.[=14 提供更短的解决方案=]

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

您可以尝试在下面使用 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

最好的方法是使用 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