62,198
社区成员
发帖
与我相关
我的任务
分享
create table t_1(code varchar(10),parent varchar(10))
insert into t_1(code,parent)
select 'A ', '0 '
union all select 'E ', 'A '
union all select 'E01 ', 'E '
union all select 'E02 ', 'E '
create table t_2(code varchar(10),value int)
insert into t_2(code,value)
select 'E01 ',3
union all select 'E02 ',4
--递归取下级
create function f_getchild(@code varchar(10))
returns @t table(code varchar(10))
as
begin
declare @t_temp table(id int identity(1,1),child varchar(10))
insert into @t(code)
select code from t_1 where Parent = @code
insert into @t_temp(child)
select code from t_1 where Parent = @code
declare @child_temp varchar(10),@max_id int,@min_id int
select @max_id = max(id),@min_id = min(id) from @t_temp
while @min_id <= @max_id
begin
select @child_temp = child from @t_temp where id = @min_id
insert into @t(code)
select * from dbo.f_getchild(@child_temp)
select @min_id = @min_id + 1
end
return
end
--调用
select code from dbo.f_getchild( 'E01 ')
CREATE TABLE #origin(id varchar(4) NOT NULL,parentid varchar(4) NULL,typeid varchar(4) NULL) ON [PRIMARY]
ALTER TABLE #origin ADD CONSTRAINT PK_Table1 PRIMARY KEY CLUSTERED (id)
Insert into #origin values(1,0,4);
Insert into #origin values(2,1,4);
Insert into #origin values(3,2,4);
Insert into #origin values(4,1,4);
Insert into #origin values(5,3,4);
Insert into #origin values(6,5,2);
declare @pageSize int;
declare @pageIndex int;
declare @typeid varchar(10);
declare @rows int;
declare @parentid varchar(10);
--设置初始变量
set @pageSize = 1;
set @pageIndex = 3;
set @typeid = 4;
--创建临时表
create table #tmp (id varchar(10),parentid varchar(10));
--插入记录数
WITH OrderedTbl AS (select id,parentid,row_number() OVER(order BY id) AS 'ROWSID' from #origin where typeid=@typeid)
insert into #tmp SELECT id,parentid FROM OrderedTbl WHERE ROWSID BETWEEN @pageSize * (@pageIndex -1) and @pageSize * @pageIndex
--寻找父节点数据
declare findParent cursor for select parentid from (select distinct parentid from #tmp ) a where parentid not in (select distinct id from #tmp)
open findParent
fetch next from findParent into @parentid
while @@fetch_status =0
begin
insert into #tmp select id,parentid from #origin where id=@parentid
fetch next from findParent into @parentid
end
close findParent;
DEALLOCATE findParent
--显示所有数据
select * from #tmp order by id,parentid
--清理现场
drop table #tmp
drop table #origin