首页 > 解决方案 > 用于生成计算列的用户定义标量函数

问题描述

我的数据库有 2 个表,即(分期付款和分期付款计划)。在分期付款表中有列数。我想添加一个新的计算列名称 SurchargeCalculated (SC)。SC的计算是这样的

SC = (Installment.Amount * Installment.days * (InstallmentPlan.InstPercentage /365 /100)) 

我创建了用户定义函数 SurchargeCal,它有 3 个参数,即 Amount、days 和 InstPercentage。问题是当我在分期付款表中添加计算列并从那里调用标量函数时,saclar 函数需要第二个表(InstallmentPlan)的 InstPercetage 参数。我知道推荐的方法是使用视图,但这会使我的问题复杂化,因为我在 C# 中使用分期付款表。

任何帮助将不胜感激。

我的标量函数是

USE [myDB]
GO
/****** Object:  UserDefinedFunction [dbo].[SurchargeCal]    Script Date: 17/02/2020 2:21:15 PM 
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER FUNCTION [dbo].[SurchargeCal] 
(
    -- Add the parameters for the function here
    @days as int,
    @amount as money,
    @surchargePerc as decimal
)
RETURNS decimal
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result as decimal =0;

    -- Add the T-SQL statements to compute the return value here
    --SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1>

        if  @days = 0
            set @result = 0
        else if (@days > 0 and @amount > 0)
            set @result = (@days * @amount * (@surchargePerc/ 365 / 100))
        else
            set @result = 0


    -- Return the result of the function
    RETURN @result

END

然后下面的 ADD table 命令 XXXX 是问题

USE [myDB]
GO
ALTER TABLE dbo.Installment  
ADD SurchargeCalculated AS dbo.SurchargeCalc(days,Amount, XXXX) --where XXX should be InstPercenatage
GO

标签: sql-serverentity-frameworkc#-4.0user-defined-functions

解决方案


由于您不能直接在计算列上使用子查询,因此您需要在标量函数本身上执行此操作:

CREATE FUNCTION SurchargeCal(@days as integer, @amount as money, @PlanKey as integer)
RETURNS decimal
AS
BEGIN
    DECLARE @result as decimal = 0;

    SELECT @result = @amount * @days * InstPercentage / 365 / 100
    FROM InstallMentPlan 
    WHERE PlanKey = @PlanKey    

    RETURN @result   
END

现在您可以创建计算列,传递 PlanKey 而不是其 InstPercentage。

ALTER TABLE dbo.Installment  
ADD SurchargeCalculated AS dbo.SurchargeCalc(days, Amount, PlanKey)

推荐阅读