问题
I have databse having 2 tables i.e (Installment and InstallmentPlan). In the installment table there are number of columns. I want to add one new computed column name SurchargeCalculated (SC). The calculation for SC is this
SC = (Installment.Amount * Installment.days * (InstallmentPlan.InstPercentage /365 /100))
I have created user-defined function SurchargeCal having 3 parameters which are Amount, days and InstPercentage. The problem is that when i add computed column in installment table and call scalar function from there, the saclar func needs InstPercetage parameter of 2nd table (InstallmentPlan). I know recommended ways is to use view but that will complicate my problem as i am using installment table in C#.
Any help will be extremely appreciated.
My scalar function is
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
then below ADD table command XXXX is the problem
USE [myDB]
GO
ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days,Amount, XXXX) --where XXX should be InstPercenatage
GO
回答1:
Since you can't use a subquery directly on the computed column, you will need to do it on the scalar function itself :
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
Now you can create the computed column, passing the PlanKey instead of its InstPercentage.
ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS dbo.SurchargeCalc(days, Amount, PlanKey)
来源:https://stackoverflow.com/questions/60264633/user-defined-scalar-function-to-generate-computed-column