日期:2014-05-17  浏览次数:20471 次

实在不行了,求一sql自定义函数
表结构是这样子的
ddays   dfees
.00 3.00
12.00 7.00
18.00 5.00
26.00 8.00
31.00 3.00


ddays 字段是天数 dfees字段是单价

在0到12天(不包括12)天的时候单是3块钱
在12到18天(不包括18)天的时候单是7块钱
在18到26天(不包括26)天的时候单是5块钱

请问如何写一个sql函数实现上面的功能;
create function DayJiaGe(days decimal(18,2))

如果输入DayJiaGe(4)则返回:3
如果输入DayJiaGe(12)天则返回:3,7
如果输入DayJiaGe(19)天则返回:3,7,5

------解决方案--------------------
假設(表结构是这样子的ddays   dfees)表名是test01,創建自定義函數的代碼如下:

CREATE function [dbo].[DayJiaGe](@days decimal(18,2))
RETURNS varchar(max)
AS
BEGIN
declare @RETURN varchar(max)
;
with a1 as
(
select 'a' gr,ddays,dfees from test01 where ddays<=@days
)
,a2 as
(
SELECT a.gr,dfees=
(select RTRIM(cast(dfees as char(20)))+',' as [text()]
from a1 b where a.gr=b.gr
for xml path('')
) FROM a1 a group by a.gr
)
select @RETURN=replace(replace(dfees,'.00,',','),'0,',',') from a2
return left(@RETURN,len(@RETURN)-1)
END

------解决方案--------------------
代碼簡化版:
create function [dbo].[DayJiaGe](@days decimal(18,2))
RETURNS varchar(max)
AS
BEGIN
declare @RETURN varchar(max)
;
with a1 as
(
select dfees from test01 where ddays<=@days
)
,a2 as
(
SELECT dfees=
(select RTRIM(cast(dfees as char(20)))+',' as [text()]
from a1 b where 1=1
for xml path('')
) FROM a1 a
)
select @RETURN=replace(replace(dfees,'.00,',','),'0,',',') from a2
return left(@RETURN,len(@RETURN)-1)
END

------解决方案--------------------
Create function fn_Dfees(
@days decimal(18,2)
)
returns varchar(200)
as
begin 
declare @str varchar(200)
set @str=stuff( (select ','+rtrim(cast(dfees as int)) from table1 where ddays<=@days order by ddays for xml path('')),1,1,'')
return @str
end

------解决方案--------------------

IF OBJECT_ID('T_CSDN_ONE') IS NOT NULL
BEGIN
  DROP TABLE dbo.T_CSDN_ONE;
END
GO
CREATE TABLE T_CSDN_ONE
(
   DDAYS INT,
   DFEES DECIMAL(12,2)
)

INSERT INTO dbo.T_CSDN_ONE
        ( DDAYS,DFEES )
SELECT 0,3
UNION ALL
SELECT 12,7
UNION ALL
SELECT 18,5
UNION ALL
SELECT 26,8
UNION ALL
SELECT 31,3
GO
CREATE FUNCTION DayJiaGe(@SDAY INT)