34,872
社区成员
发帖
与我相关
我的任务
分享CREATE FUNCTION fGetRuleMoney(
@InputMoney Money,
@RuleMode nVarChar(512),
@Par1 nVarChar(20)--分隔符
) RETURNS MONEY
AS
BEGIN
DECLARE @Amount MONEY
SET @Amount=0
DECLARE @T TABLE(Col1 INT,Col2 INT,ID int)
INSERT INTO @T
SELECT
Col1=LEFT(Col,CHARINDEX(N'送',Col)-1),Col2=SUBSTRING(Col,CHARINDEX(N'送',Col)+1,LEN(Col)),ID=ROW_NUMBER()OVER(ORDER BY LEFT(Col,CHARINDEX(N'送',Col)-1)*1 desc)
FROM
(
SELECT Col=substring(@RuleMode,b.number,charindex(',',@RuleMode+',',b.number)-b.number) FROM master.dbo.spt_values AS b
WHERE b.type='P' AND charindex(',',','+@RuleMode,b.number)=b.number --也可用 substring(','+@RuleMode,b.number,1)=','
)t
WHILE EXISTS(SELECT * FROM @T WHERE Col1<=@InputMoney)
BEGIN
SELECT TOP 1 @Amount=@Amount+Col2 FROM @T WHERE Col1<=@InputMoney ORDER BY ID
SET @InputMoney=@InputMoney-ISNULL((SELECT MAX(Col1) FROM @T WHERE Col1<=@InputMoney),0)
END
RETURN @Amount
END
go
Select dbo.fGetRuleMoney(3600, N'500送20,1000送50,2000送150', ',') --为220
/*
220.00
*/
Select dbo.fGetRuleMoney(1200, '500送20,1000送50,2000送150', ', ') --为50
/*
50.00
*/