日期:2014-05-18  浏览次数:20503 次

sql如何遍历所有子栏目

表结构
ID   Name   ParentID
1     栏目     0
2     栏目     0
3     栏目     0
4     栏目     1
5     栏目     1
6     栏目     4

第一个问题:如何用sql语句把子栏目给列出来?
第二个问题:select   *   from   table   where   ID   in   (1,2,3,4)
如果把(1,2,3,4)用变量来表示,又该如何?好像mssql没有数组吧?




------解决方案--------------------
select * from table where ID in (1,2,3,4)

1 栏目 0
2 栏目 0
3 栏目 0
4 栏目 1
----------
这个结果的意义是?子栏目?

------解决方案--------------------
看错了,是两个问题,呵呵。
------解决方案--------------------
--这个方法不是我原创的。
--1)定义示范数据表,这里是3层目录树(可以任意层)
declare @aTable table (id int ,parentid int, foldername varchar(10))
insert into @aTable values (1,null, '栏目 ')
insert into @aTable values (2,null, '栏目 ')
insert into @aTable values (3,null, '栏目 ')
insert into @aTable values (4,1, '栏目 ')
insert into @aTable values (5,1, '栏目 ')
insert into @aTable values (6,4, '栏目 ')

--2)获取需要复制的目录ID列表

declare @idtable table(id int,parentid int, foldername varchar(10))
insert into @idtable
select id,parentid ,foldername
from @aTable
where id = 1--父ID
while @@ROWCOUNT> 0
begin
insert into @idtable
select b.id,b.parentid,b.foldername
from @idtable a join @aTable b on a.id=b.parentid
where not exists (select 1 from @idtable where id=b.id)

end


select * from @idtable

id parentid foldername
----------- ----------- ----------
1 NULL 栏目
4 1 栏目
5 1 栏目
6 4 栏目
------解决方案--------------------
第二个问题,比较笨的办法
declare @str varchar(8000)
set @str = '1,2,3,4 '
select * from table where @str like '% '+ convert(varchar(10),id) + '% '