急!!求一SQL

jastion 2004-06-25 11:18:43
---現有資料如下
--UID 與 PUID子父關系

UID UName PUID
1 aa 0
2 bb 0
3 cc 1
4 dd 1
5 dd 3


--現在我想要一個函數 GetFather(@UID int )返回的資料為期父的資料
--(即知道他的子,想求他的父)
select GetFather(1)
--返回空
--------------------------------------------
select GetFather(3)
--返回
1 aa 0
select GetFather(5)
--返回
1 aa 0
3 cc 1
...全文
66 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2004-06-25
  • 打赏
  • 举报
回复
--测试

--测试数据
create table 资料表(UID int,UName varchar(10),PUID int)
insert 资料表 select 1,'aa',0
union all select 2,'bb',0
union all select 3,'cc',1
union all select 4,'dd',1
union all select 5,'dd',3
go

--查询的函数
create function GetFather(@UID int)
returns @re table(uid int,level int)
as
begin
declare @l int
set @l=0
insert @re select puid ,@l from 资料表
where uid=@uid and puid<>0
while @@rowcount>0
begin
set @l=@l+1
insert @re select puid,@l
from 资料表 a join @re b on a.uid=b.uid and b.level=@l-1
end
return
end
go

--调用实现查询
select a.* from 资料表 a join GetFather(5) b on a.uid=b.uid
go

--删除测试
drop table 资料表
drop function GetFather

/*--测试结果

UID UName PUID
----------- ---------- -----------
1 aa 0
3 cc 1

(所影响的行数为 2 行)

--*/
zjcxc 元老 2004-06-25
  • 打赏
  • 举报
回复
--处理函数
create function GetFather(@UID int)
returns @re table(uid int,level int)
as
begin
declare @l int
set @l=0
insert @re select puid ,@l from 资料表
where uid=@uid and puid<>0
while @@rowcount>0
begin
set @l=@l+1
insert @re select puid,@l
from 资料表 a join @re b on a.uid=b.uid and b.level=@l-1
end
return
end
go

--调用实现查询
select a.* from 资料表 a join GetFather(5) b on a.uid=b.uid

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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