如何实现这样表的选择????

ahone 2007-12-26 09:13:49
表 A
id fid tid
1 12 5
2 22 12
3 24 22
4 26 null


如果输入tid=5

则输出:
id fid tid
1 12 5
2 22 12
3 24 22

就是根据fid和tid之间的关联选择结果,12继承自5,22又继承自12,24又继承自22 所有上面结果
请教sql的写法.
分不够会追加
...全文
120 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
leo_lesley 2007-12-26
  • 打赏
  • 举报
回复
create table A (id  int, fid  int,tid int)
insert A
select 1 , 12 , 5
union select 2 , 22 , 12
union select 3 , 24 , 22
union select 4 , 26 ,null
go
create function f(@val int)
returns varchar(8000)
as
begin
declare @str varchar(1000),@fid varchar(100)

select @str=isnull(@str,'')+','+rtrim(id),@fid=isnull(@fid,'')+rtrim(fid) from A t where tid=@val
while @@rowcount>0
begin
select @str=@str+','+rtrim(id),@fid=rtrim(fid) from A t where tid=@fid
end
set @str=@str+','
return @str
end
go
select * from A where charindex(','+rtrim(id)+',',dbo.f(5))>0

drop function f
drop table A


/* 结果
id fid tid
----------- ----------- -----------
1 12 5
2 22 12
3 24 22

(所影响的行数为 3 行)
*/
leo_lesley 2007-12-26
  • 打赏
  • 举报
回复
create table A (id  int, fid  int,tid int)
insert A
select 1 , 12 , 5
union select 2 , 22 , 12
union select 3 , 24 , 22
union select 4 , 26 ,null


declare @str varchar(1000),@fid varchar(100)
select @str=isnull(@str,'')+','+rtrim(id),@fid=isnull(@fid,'')+rtrim(fid) from A t where tid=5
while @@rowcount>0
begin
select @str=@str+','+rtrim(id),@fid=rtrim(fid) from A t where tid=@fid
end
select * from A where charindex(','+rtrim(id)+',',@str+',')>0

drop table A
ahone 2007-12-26
  • 打赏
  • 举报
回复
就是父子关系 "所有上面结果"---->"所以有上面结果"
昵称被占用了 2007-12-26
  • 打赏
  • 举报
回复

--写个函数
create function fn_Records(
@Tid int
)
returns @R table (Id int,fid int,tid int)
as
begin
insert @r select Id,fid,tid from a where tid=@Tid
while exists (select 1 from a where tid in (select fid from @r) and id not in (select id from @R))
insert @r select Id,fid,tid from a where tid in (select fid from @r) and id not in (select id from @R)
return
end
go

--调用
select * from dbo.fn_Records(5)

areswang 2007-12-26
  • 打赏
  • 举报
回复
你说的继承是个什么关系?

34,837

社区成员

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

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