sql-server - 用于生成计算列的用户定义标量函数
问题描述
我的数据库有 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
解决方案
由于您不能直接在计算列上使用子查询,因此您需要在标量函数本身上执行此操作:
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)
推荐阅读
- python - 另一个文件中的 Scrapy 回调函数
- c# - Xamarin.Forms:将项目从代码隐藏添加到 ListView 而不绑定?
- c - 错误:可变大小的对象可能未在 c 语言中初始化。常量 int 与它有什么关系?
- java - 向第三方应用程序公开 Web 服务?
- exif - 是什么让一些 EXIF 标签不可写?
- java - 无法从 /mnt/media_rw/ 获取文件
- bash - 无法让 psql 命令在 bash 脚本中运行
- javascript - 创建 jQuery 插件时如何使用 ES6 模块?
- java - 如何在绘画时将旧位图显示到 DrawingView
- canvas - (Kotlin) 从内部存储加载文件并使用它在画布上绘图