user978122
user978122

Reputation: 5761

Recursive SQL Query: One entry ponting to another, and traversing it

I am trying to write a SQL query (for SQl Server), and am curious if there is a simple method to achieve my ends. I will simplify things to get to the heart of the matter:

I have a table with two columns, which we can call column A and column B. Column A contains the name of a segmented file, and column B contains the next part of the segmented file. So, I can have multiple segments pointing to multiple segments.

So, for example:

Column A     Column B
File 1       File 2
File 2       File 3
File 3       File 4
File 7       File 13

I need to get a list of all the segments starting with File 1 and ending with File 4, preferably in one column. Or, to put it another way, I need to start with a given entry in column A, and having something traverse and dereference entries from column B, until no entry can be found from column B in column A.

Something like SELECT allsegments() From FTable WHERE FTable.A = "File 1"? Or do you think I need to write some custom code?

Upvotes: 3

Views: 165

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

Using a recursive CTE it can look something like this:

declare @T table
(
  ColumnA varchar(10),
  ColumnB varchar(10)
);

insert into @T values  
('File 1',       'File 2'),
('File 2',       'File 3'),
('File 3',       'File 4'),
('File 7',       'File 13');

with C as
(
  select T.ColumnA,
         T.ColumnB,
         cast(T.ColumnA+','+T.ColumnB as varchar(max)) as Comb
  from @T as T
  where T.ColumnA = 'File 1'
  union all
  select T.ColumnA,
         T.ColumnB,
         C.Comb+','+T.ColumnB 
  from @T as T
    inner join C
      on T.ColumnA = C.ColumnB
)
select top 1 Comb
from C
order by len(Comb) desc
option (maxrecursion 0)

Result:

Comb
------------------------
File 1,File 2,File 3,File 4

Default maxrecursion is 100 so if you have more than 100 files in a chain you need to specify the number of allowed recursions. option (maxrecursion 0) makes the max number unlimited.

Upvotes: 2

user1049838
user1049838

Reputation:

select path from 
(
   select connect_by_isleaf leaf, sys_connect_by_path(von, '/') path
     from table1
    start with A = 'File x'
  connect by   A = prior B
) where path like '%File y';

=> This query returns the possible paths from File x to File y, seperated by / or any delimiter of your choice.

Upvotes: 0

Related Questions