当前位置: 代码迷 >> Sql Server >> 有关自连接的查询有关问题(。)
  详细解决方案

有关自连接的查询有关问题(。)

热度:3   发布时间:2016-04-27 15:21:23.0
有关自连接的查询问题(在线等。。。)
如题,表如下:
id(int)         name(nvarchar)           parent_id(int)
      1                           pp1_1                             0
      2                           pp2_1                             0
      3                           pp3_2                             1
      4                           pp4_2                             2
      5                           pp5_3                             3
      6                           pp6_4                             5

现在需要一个存储过程,接收id为参数(比如输入6),结果集中要包含id为
6这条记录和他的parent_id,parent_id要一直到1(根)
例如:输入6
结果中包含 6 5 3 1
不知道我说清楚没有,请高手帮忙~在线等

------解决方案--------------------
Create proc getY(@id int)
as
declare @a table(id int, name nvarchar(30), parent_id int)
insert @a select 1 , 'pp1_1 ', 0
union all select 2 , 'pp2_1 ', 0
union all select 3 , 'pp3_2 ', 1
union all select 4 , 'pp4_2 ', 2
union all select 5 , 'pp5_3 ', 3
union all select 6 , 'pp6_4 ', 5

if object_id( 'tab ') is not null
drop table tab
declare @s varchar(1000)
declare @v varchar(1000)
declare @I int
declare @L int

set @l=0
set @[email protected]
set @s= 'Create table tab( '
set @v= 'Insert into tab select '
while exists(select 1 from @a where [email protected])
begin

select @[email protected]+ 'a '+ltrim(@l)+ ' int, '
select @[email protected]+ltrim(@id)+ ', '
select @id=parent_id from @a where [email protected]
set @[email protected]+1
end
if @l=0
begin
select '无 ' as '无 '
return
end
select @s=left(@s,len(@s)-1)+ ') '
exec(@s)
select @v=left(@v,len(@v)-1)
exec(@v)
select * from tab

=====================
getY 6
------解决方案--------------------
CREATE PROCEDURE [getid]
@id int
AS
while @id <> 0
begin
select id from table1 id = @id
select @id = parent_id from id = @id
end
GO
  相关解决方案