如就是你上表的数据就简单了
select * from table where fatherid<>0如果还有别的数据就要知道一个对应的关系才行
select * from table where fatherid<>0如果还有别的数据就要知道一个对应的关系才行
解决方案 »
- 简单sql求优化
- SQL Server 2005求tsql:已知学生成绩表,查询出分数段和平均分及格率表,最好是视图代码
- 存储过程中的set identity_insert <table> on的作用?
- 关于bulk insert的问题
- 关于sql语句的问题
- 请问:sql server 2000中,如何将一数据库的存储过程导到另一数据库中呢?谢谢!
- sql 时间截取
- 给出一个日期,求是星期几的函数?
- 比较难实现的表格转子换问题
- tempdb数据库增长占满磁盘怎么办?
- 用创建存储过程向导生成的存储过程如下: 请问怎样把生成的字段后面的数字 1,2,3,4 ……去掉? 只用数据库里面的字段名来表示?
- 请问,能在WIN2003里面装SQL2000么?
create function f_cid(
@id int
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from tb a,@re b
where a.fatherid=b.id and b.level=@l-1
end
/*--如果只显示最明细的子(下面没有子),则加上这个删除
delete a from @re a
where exists(
select 1 from tb where fatherid=a.id)
--*/
return
end
go--调用(查询所有的子)
select a.*,层次=b.level from tb a,f_cid(1)b where a.id=b.id
go
--作者: 邹建--示例数据
create table tb(id int identity(1,1),pid int,name varchar(20))
insert tb select 0,'中国'
union all select 0,'美国'
union all select 0,'加拿大'
union all select 1,'北京'
union all select 1,'上海'
union all select 1,'江苏'
union all select 6,'苏州'
union all select 7,'常熟'
union all select 6,'南京'
union all select 6,'无锡'
union all select 2,'纽约'
union all select 2,'旧金山'
go--查询指定id的所有子
create function f_cid(
@id int
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from tb a,@re b
where a.pid=b.id and b.level=@l-1
end
return
end
go--调用(查询所有的子)
select a.*,层次=b.level from tb a,f_cid(2)b where a.id=b.id
go--删除测试
drop table tb
drop function f_cid/*--测试结果id pid name 层次
----------- ----------- -------------------- -----------
2 0 美国 0
11 2 纽约 1
12 2 旧金山 1(所影响的行数为 3 行)
--*/
select id,fatherId
from 表 a
where a.Fatherid = 给定值
or a.Fatherid in ( select Id
from 表 c
where c.Fatherid = 给定值 )