日期:2014-05-17 浏览次数:20491 次
CREATE TABLE #tmptbl (accountcod VARCHAR(20),parentcod VARCHAR(20),credit NUMERIC(20,5), debit NUMERIC(20,5))
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('A','',200,120)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('A01','A',220,350)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('A0101','A01',150,740)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('B','',200,620)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('B01','B',520,280)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('B0101','B01',500,320)
INSERT INTO #tmptbl (accountcod,parentcod,credit,debit) VALUES ('B0102','B01',400,120)
SELECT * FROM #tmptbl
go
if OBJECT_ID('tab') is not null
drop table tab
if OBJECT_ID('get_level')is not null
drop function get_level
go
CREATE TABLE tab (accountcod VARCHAR(20),parentcod VARCHAR(20),credit NUMERIC(20,5), debit NUMERIC(20,5))
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('A','',200,120)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('A01','A',220,350)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('A0101','A01',150,740)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('B','',200,620)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('B01','B',520,280)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('B0101','B01',500,320)
INSERT INTO tab (accountcod,parentcod,credit,debit) VALUES ('B0102','B01',400,120)
--select * from tab
go
create function get_level(@id varchar(10))
returns @tab table(accountcod varchar(10),[level] int)
as begin
declare @lev int=1
insert into @tab
select accountcod,@lev from tab where accountcod=@id
while (@@rowcount>0)
begin
set @lev=@lev+1
insert into @tab
select t1.accountcod,@lev from tab t1,@tab t2
where t2.accountcod=t1.parentcod and [level]=@lev-1
end
return
end
go
--select * from get_level('A')
with sel&