金额合计求值问题

原帖地址:

http://community.csdn.net/Expert/topic/3190/3190686.xml?temp=.6296961

表test中记录:
  aa     bb 
  001   50.5
  002   60
  003   15.4
  004   25
  005   48
  ...

输入任一金额,然后在表中查找是否有该金额或几条记录的合计等于该金额.
如:输入25,则要找出004,输入85,则要找出002与004,依次类推。
------------------------------------------------------------------------------------


--测试数据
create table test(aa varchar(10),bb numeric(10,2))
insert test select '001',50.5
union  all  select '002',60
union  all  select '003',15.4
union  all  select '004',25
union  all  select '005',48
union  all  select '006',37
go

--查询函数
create function fn_search(@Num numeric(10,2))
returns @r table (aa varchar(10),bb numeric(10,2))
as
begin
 declare @t table (aa varchar(8000),aa1 varchar(10),bb numeric(10,2),level int)
 declare @l int

 insert @r select aa,bb from test where bb=@num
 if @@rowcount>0 goto lb_exit

 set @l=0
 insert @t select ','+aa+',',aa,bb,@l from test where bb<@num
 while @@rowcount>0
 begin
  insert @r select distinct a.aa,a.bb
  from test a,(
   select a.aa,a.bb,aa1=b.aa from test a,@t b
   where b.level=@l
    and b.aa1<a.aa
    and a.bb=@num-b.bb
  )b where a.aa=b.aa or charindex(','+a.aa+',',b.aa1)>0
  if @@rowcount>0 goto lb_exit

  set @l=@l+1
  insert @t select b.aa+a.aa+',',a.aa,a.bb+b.bb,@l
  from test a,@t b
  where b.level=@l-1
   and b.aa1<a.aa
   and a.bb<@num-b.bb
 end

lb_exit:
 return
end
go

--调用测试1
select * from dbo.fn_search(25)

/*--结果

aa         bb          
---------- ------------
004        25.00

(所影响的行数为 1 行)
--*/

--调用测试2
select * from dbo.fn_search(135.5)

/*--结果

aa         bb          
---------- ------------
001        50.50
002        60.00
004        25.00
005        48.00
006        37.00

(所影响的行数为 5 行)
--*/

--调用测试3(找不到的,无返回值)
select * from dbo.fn_search(135.7)

/*--结果
aa         bb          
---------- ------------

(所影响的行数为 0 行)
--*/
go

drop table test
drop function fn_search

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值