树的查询,通过名字查id

xuanzg 2004-08-14 05:38:36
有表aaa,
字段: id, name, parentid
数值: 1 a <null>
2 b 1
3 c 2
4 d 2

给定一字符串值, 如,a/b/d
能求出 d的id: 4来

应该如何作?
谢谢大家了!
...全文
215 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2004-08-14
  • 打赏
  • 举报
回复
以最后这个函数为准
zjcxc 2004-08-14
  • 打赏
  • 举报
回复
--示例

--示例数据
create table aaa(id int,name varchar(10),parentid int)
insert aaa select 1,'a',null
union all select 2,'b',1
union all select 3,'c',2
union all select 4,'d',2
go

--查询函数
create function f_qry(
@str varchar(800)
)returns int
as
begin
declare @t table(id int,level int,sid varchar(8000))
declare @l int,@s varchar(8000)

select @s=@str,@l=0

insert @t select id,@l,name
from aaa
where parentid is null
and @str+'/' like name+'/%'
while @@rowcount>0 and @s<>''
begin
select @s=stuff(@s,1,charindex('/',@s+'/'),''),@l=@l+1

insert @t select a.id,@l,b.sid+'/'+a.name
from aaa a,@t b
where a.parentid=b.id and b.level=@l-1
and @s+'/' like a.name+'/%'
end
return((select id from @t where sid=@str))
end
go

--调用函数实现查询
select dbo.f_qry('a/b/d')
go

--删除测试
drop table aaa
drop function f_qry

/*--测试结果


-----------
4

(所影响的行数为 1 行)
--*/
zjcxc 2004-08-14
  • 打赏
  • 举报
回复
--稍改一个,加多一个限制就行了.

--查询函数
create function f_qry(
@str varchar(800)
)returns int
as
begin
declare @id int
select @id=id,@str=stuff(@str,1,charindex('/',@str+'/'),'')
from aaa
where parentid is null --加多一个条件,保证是从最顶一级开始查询就行了
and @str+'/' like name+'/%'
while @@rowcount>0 and @str<>''
select @id=id,@str=stuff(@str,1,charindex('/',@str+'/'),'')
from aaa
where parentid=@id and @str+'/' like name+'/%'
return(@id)
end
xuanzg 2004-08-14
  • 打赏
  • 举报
回复
zjcxc(邹建) 老大快来救火亚!
xuanzg 2004-08-14
  • 打赏
  • 举报
回复
谢谢老大

但还差一步
由于name 字段不唯一
可能你的第一步就出现问题了
select @id=id,@str=stuff(@str,1,charindex('/',@str+'/'),'')
from aaa
where @str+'/' like name+'/%'
搜寻出来好多个结果只要了其中的一个
例如
字段: id, name, parentid
数值: 1 a <null>
2 b 1
3 c 2
4 d 2
5 f 1
6 a 5

这样你的函数就执行不对了

zjcxc 2004-08-14
  • 打赏
  • 举报
回复
--示例

--示例数据
create table aaa(id int,name varchar(10),parentid int)
insert aaa select 1,'a',null
union all select 2,'b',1
union all select 3,'c',2
union all select 4,'d',2
go

--查询函数
create function f_qry(
@str varchar(800)
)returns int
as
begin
declare @id int
select @id=id,@str=stuff(@str,1,charindex('/',@str+'/'),'')
from aaa
where @str+'/' like name+'/%'
while @@rowcount>0 and @str<>''
select @id=id,@str=stuff(@str,1,charindex('/',@str+'/'),'')
from aaa
where parentid=@id and @str+'/' like name+'/%'
return(@id)
end
go

--调用函数实现查询
select dbo.f_qry('a/b/d')
go

--删除测试
drop table aaa
drop function f_qry

/*--测试结果


-----------
4

(所影响的行数为 1 行)
--*/
xuanzg 2004-08-14
  • 打赏
  • 举报
回复
不是你说的这样的
我的意思是通过父子关系来找的这个字串的id值
通过字符串值,a/b/d
因该能够列出id的组合 1/2/4,
然后去id 4
不能只查name
name不是唯一的,有很多相同的纪录,
qiliu 2004-08-14
  • 打赏
  • 举报
回复
不明白什么意思!!
declare @s varchar(255)
set @s='a/b/d'
select top 1 id from aaa
where name =right(@s,1)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧