Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 sql recursion

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2006-06-12 : 09:51:49
dan writes "Hi I an having a hard time comming up with a sql query - i think it involves recusrsion.

Here is the situation:

--------------------------
name |Old Friend's Name
--------------------------
1 |
2 |1
3 |
4 |1
5 |2
6 |3
--------------------------

I want a query that returns Old Friend's names of '1'.
They may be his friend's or his friend's friends

eg. FriendsOf(1) should return 2,4,5
5 is related to 1 via 2

Thanks"

blindman
Master Smack Fu Yak Hacker

2365 Posts

Posted - 2006-06-12 : 11:26:50
So do you only want to go down two plys (friends friends) or N plys (friends friends friends...)?
Go to Top of Page

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2006-06-13 : 10:58:21
Something like this?

--data
declare @t table (name int, OldFriendsName int)
insert @t
select 1, null
union all select 2, 1
union all select 3, null
union all select 4, 1
union all select 5, 2
union all select 6, 3

--input
declare @name int
set @name = 1

--calculation
declare @OldFriends table (name int)
insert @OldFriends select @name

while @@rowcount > 0
begin
insert @OldFriends
select b.name from @OldFriends a
inner join @t b on a.name = b.OldFriendsName
where b.name not in (select name from @OldFriends)
end

select * from @OldFriends where not name = @name order by name

/*results
name
-----------
2
4
5
*/


Ryan Randall
www.monsoonmalabar.com London-based IT consultancy

Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page
   

- Advertisement -