原帖地址:
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 [email protected]
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 [email protected]
and b.aa1<a.aa
and [email protected]
)b where a.aa=b.aa or charindex(','+a.aa+',',b.aa1)>0
if @@rowcount>0 goto lb_exit
set @[email protected]+1
insert @t select b.aa+a.aa+',',a.aa,a.bb+b.bb,@l
from test a,@t b
where [email protected]
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