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 2005 Forums
 Transact-SQL (2005)
 Recursion SQL

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2007-03-02 : 08:46:50
Mel writes "Creating SQL for the following problem has so far eluded me. Can you help?

I have a table containing tasks, e.g.

1 Install pump
2 Remove pump
3 Install valve
4 Remove valve
5 Overhall engine
6 Assemble engine

The training supervisor states that if a staff member is trained to do a certain task, then that training may also be sufficient for other tasks. I therefore have a table with 'explicit' training equivalents, e.g

Task Equivalent
1 3
2 4
2 3

I want SQL to produce the results of all equivalents. I.e, if 1 = 3, then 3 = 1, if 6 = 1 and 1 = 3 then 6 = 3. So from the above, I want to generate:

1 3
3 1
2 4
4 2
2 3
3 2 (These are the easy ones!)
1 2 (Implied relations :)
2 1
3 4
4 3

In this example there are only a few implied results, but there could potentially be many, causing multiple recursion.

Can you help?"

gurpleman
Starting Member

2 Posts

Posted - 2007-03-02 : 12:43:49
I think some minor modifications to the following snippet may accomplish what you're trying to do:
http://www.competitivechainsmoking.com/ramblings/index.php?blog=tech#recursivejoin


Kyle
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-03-02 : 14:34:21
[code]-- prepare sample data
declare @t table (task int, equivalent int)

insert @t
select 1, 3 union all
select 2, 4 union all
select 2, 3

-- stage data
declare @s table (t1 int, t2 int)

insert @s
select task, equivalent from @t
union
select equivalent, task from @t

while @@rowcount > 0
insert @s
select o.t2, e.t1 from @s as o
inner join @s as e on e.t1 = o.t2
left join @s as s on s.t1 = o.t2 and s.t2 = e.t1
where s.t1 is null

-- show the expected output
select distinct * from @s order by t1, t2[/code]

Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -