在sql server 2008 r2上工作,在递归计费量计算过程中需要帮助。想写一个sp,在我的sp中我需要根据参数头和给定量来计算头总和: 图片描述我的数据库输入集,从输入集我需要计算给定头上的总电荷量,
我的表格脚本:
CREATE TABLE [dbo].[testCharge](
[Head] [int] NULL,
[Amount] [decimal](18, 6) NULL,
[IsPercent] [bit] NULL,
[Head Percent] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[testCharge] ([Head], [Amount], [IsPercent], [Head Percent]) VALUES (100, CAST(10.000000 AS Decimal(18, 6)), 1, 103)
INSERT [dbo].[testCharge] ([Head], [Amount], [IsPercent], [Head Percent]) VALUES (101, CAST(10.000000 AS Decimal(18, 6)), 1, 102)
INSERT [dbo].[testCharge] ([Head], [Amount], [IsPercent], [Head Percent]) VALUES (102, CAST(50.000000 AS Decimal(18, 6)), 0, NULL)
INSERT [dbo].[testCharge] ([Head], [Amount], [IsPercent], [Head Percent]) VALUES (103, CAST(20.000000 AS Decimal(18, 6)), 1, 101)
使用下面的语法来检索值,这里的问题是如何在CTE上计算。
DECLARE @HeadID INT = 103 ;
WITH MyCTE
AS (
---get base
SELECT Head ,
[Head Percent] ,
IsPercent ,
Amount
FROM testCharge
WHERE Head = @HeadID
UNION ALL
--get base related records
SELECT charge.Head ,
charge.[Head Percent] ,
charge.IsPercent ,
charge.Amount
FROM MyCTE cte
INNER JOIN testCharge charge ON cte.[Head Percent] = charge.Head
)
SELECT *
FROM MyCTE
假设:
for my inputset-1 my head parameter is Utility and given amount is 400 sp return 10
for my inputset-2 my head parameter is Wages and given amount is 800 sp return 11
for my inputset-3 my head parameter is Utility and given amount is 500 sp return 56.1
如何递归处理输入集。
注意:我的输入已在DB中,无需考虑输入集。