查询父类下所有子类
建立数据库:
查询子类:
1
create table temptable(
2
cid int,id_name varchar(50),pid int)
3
insert into temptable values(1,'1',0)
4
insert into temptable values(2,'2',1)
5
insert into temptable values(3,'3',2)
6
insert into temptable values(4,'4',3)
7
insert into temptable values(5,'5',4)
create table temptable(2
cid int,id_name varchar(50),pid int)3
insert into temptable values(1,'1',0)4
insert into temptable values(2,'2',1)5
insert into temptable values(3,'3',2)6
insert into temptable values(4,'4',3)7
insert into temptable values(5,'5',4)查询子类:
1
select * from temptable
2
3
declare @cid varchar(2000) ;
4
declare @tempid varchar(2000) ;
5
declare @oldid varchar(2000);
6
7
set @cid='';
8
set @tempid='';
9
set @oldid='';
10
11
select @cid=@cid+Convert(varchar,cid)+',' from temptable where pid=1
12
if len(@cid)>0
13
set @cid=left(@cid,len(@cid)-1)
14
15
create table #temp(tid int)
16
set @oldid=@cid
17
18
print @cid
19
20
while len(@oldid)>0
21
begin
22
exec('insert into #temp select cid from temptable where pid in('+@oldid+')')
23
set @tempid=''
24
select @tempid=@tempid+convert(varchar,tid)+',' from #temp
25
if len(@tempid)>0
26
set @tempid=left(@tempid,len(@tempid)-1)
27
set @oldid=@tempid;
28
delete from #temp
29
set @cid=@cid+','+@tempid
30
end
31
DROP TABLE #temp
32
33
print @cid
34
35
if right(@cid,1)=','
36
set @cid=left(@cid,len(@cid)-1)
37
38
if len(@cid)>0
39
exec('select * from temptable where cid in ('+@cid+')')
40
41
select * from temptable2

3
declare @cid varchar(2000) ;4
declare @tempid varchar(2000) ;5
declare @oldid varchar(2000);6

7
set @cid='';8
set @tempid='';9
set @oldid='';10

11
select @cid=@cid+Convert(varchar,cid)+',' from temptable where pid=112
if len(@cid)>013
set @cid=left(@cid,len(@cid)-1)14

15
create table #temp(tid int)16
set @oldid=@cid17

18
print @cid19

20
while len(@oldid)>021
begin22
exec('insert into #temp select cid from temptable where pid in('+@oldid+')')23
set @tempid=''24
select @tempid=@tempid+convert(varchar,tid)+',' from #temp25
if len(@tempid)>026
set @tempid=left(@tempid,len(@tempid)-1)27
set @oldid=@tempid;28
delete from #temp29
set @cid=@cid+','+@tempid30
end31
DROP TABLE #temp32

33
print @cid34

35
if right(@cid,1)=','36
set @cid=left(@cid,len(@cid)-1)37

38
if len(@cid)>039
exec('select * from temptable where cid in ('+@cid+')')40

41

浙公网安备 33010602011771号