导航
  • 主页
  • 基础类
  • 应用实例
  • 新技术前沿

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

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的写法.
分不够会追加
...全文
85 点赞 收藏 5
写回复
5 条回复
切换为时间正序
当前发帖距今超过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
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
就是父子关系 "所有上面结果"---->"所以有上面结果"
回复

--写个函数
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
你说的继承是个什么关系?
回复
发动态
发帖子
MS-SQL Server
创建于2007-09-28

3.2w+

社区成员

MS-SQL Server相关内容讨论专区
申请成为版主
社区公告
暂无公告