金额合计求值问题

原帖地址:

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

 1<a.aa )b="" a.aa="b.aa" a.bb="@num-b.bb" and="" charindex(','+a.aa+',',b.aa1)="" or="" where="">0   
 2if @@rowcount&gt;0 goto lb_exit 
 3
 4set @l=@l+1   
 5insert @t select b.aa+a.aa+',',a.aa,a.bb+b.bb,@l   
 6from test a,@t b   
 7where b.level=@l-1   
 8and b.aa1&lt;a.aa   
 9and a.bb&lt;@num-b.bb   
10end 
11
12lb_exit:   
13return   
14end   
15go 
16
17\--调用测试1   
18select * from dbo.fn_search(25) 
19
20/*--结果 
21
22aa bb   
23\---------- ------------   
24004 25.00 
25
26(所影响的行数为 1 行)   
27\--*/ 
28
29\--调用测试2   
30select * from dbo.fn_search(135.5) 
31
32/*--结果 
33
34aa bb   
35\---------- ------------   
36001 50.50   
37002 60.00   
38004 25.00   
39005 48.00   
40006 37.00 
41
42(所影响的行数为 5 行)   
43\--*/ 
44
45\--调用测试3(找不到的,无返回值)   
46select * from dbo.fn_search(135.7) 
47
48/*--结果   
49aa bb   
50\---------- ------------ 
51
52(所影响的行数为 0 行)   
53\--*/   
54go 
55
56drop table test   
57drop function fn_search</a.aa>
Published At
Categories with 数据库类
Tagged with
comments powered by Disqus