create table ##tmp_users (id int, username nvarchar(255), parentid int )
declare @ID int
select @ID=id from t_Users t where exists
(select * from t_Users t2 where t2.id=t.parentid and t2.username='user1')
exec AddSons @ID
select * from ##tmp_users
drop table ##tmp_users
--存储
create procedure AddSons @id int
as
if exists(select * from t_Users where parentid=@id)
begin
declare @tmp_ID int
declare cur cursor for
select id from t_Users where parentid=@id
open cur
fetch next from cur into @tmp_ID
while @@FETCH_STATUS=0
begin
insert into ##tmp_users
select * from t_Users t where id=@tmp_ID
if exists(select * from t_Users where parentid=@tmp_ID)
begin
exec AddSons @tmp_ID
end
fetch next from cur into @tmp_ID
end
close cur
DEALLOCATE cur
end
--递归调用,不知道是否想要这样
SQL> select * from new;
ID USERNAME PARENTID
---------- ---------- ----------
1 user1
2 user2 1
3 user3 2
4 user4 1
SQL> select sys_connect_by_path(username,'>') "Path"
2 from new
3 start with id=1
4 connect by prior id=parentid;
Path
--------------------------------------------------------------------------------
>user1
>user1>user2
>user1>user2>user3
>user1>user4
select b.username from tablename a right outer join tablename b on a.id = b.pid where b.parentid = 1 or b.parentid is null;
是直接字节点还是包括子节点的字节点。。?