-1

I would like to be able to recursively find all relationships in a table. I have a relational table, and essentially I would like to apply the transitive property (i.e. if A~B, B~C => A~C), and with the newly found relationship(s), I would like to recursively do this until there are no more paths to be found. The data is all in SQL-Server. I have found a few other posts and tried to emulate the solutions provided with recursion. Maybe I am just not understanding how to implement my need?

To give some context:

Example contents of the relational table on SQL

A View on SQL that makes the relation multidirectional

What I would like to derive

The relational table is relating the table that the IDs come from to itself, which is why I created the multidirectional view. It made it easier to join on ID, and SELECT ID2.

Consider my table is just called relatedIDs, my view is called relatedView, and the derived view I'd like to make is called derivedView, then pulling from another post I tried something like this:

WITH RECURSIVE derivedView AS
(
  SELECT ID
  FROM relatedView
  UNION ALL
  SELECT r.ID, 
  FROM derivedView d, relatedView r
  WHERE r.ID2 = d.ID
)
SELECT * FROM derivedView;

However I am unable to really even test this as I have "Invalid Syntax near derivedView. Expecting '(', or AS" on the very first line.

As Requested SQL of creating tables and views:

/* RELATIONAL TABLE 
ID  | ID2
---------
213 | 404
404 | 605
*/
CREATE TABLE relatedIDs (
  [ID] [int] NOT NULL,
  [ID2] [int] NOT NULL,
  PRIMARY KEY (ID, ID2)
);
INSERT INTO relatedIDs VALUES (213, 404);
INSERT INTO relatedIDs VALUES (404, 605);


/* MULTIDIRECTIONAL VIEW
ID  | ID2
---------
213 | 404
404 | 213
404 | 605
605 | 404
*/
SELECT relatedIDs.ID, relatedIDs.ID2
FROM relatedIDs
UNION
SELECT relatedIDS.ID2 AS ID, relatedIDs.ID
FROM relatedIDs


/* What I'd Like to Derive: 
ID  | ID2
---------
213 | 404
404 | 213
404 | 605
605 | 404
213 | 605
605 | 213
*/
philipxy
  • 14,867
  • 6
  • 39
  • 83
  • Not trying to grill you here but since it sounds that you are relatively new to sql server you need to adapt to modern style join syntax. That comma delimited join style was replaced in ANSI-92 30 years ago. https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins – Sean Lange May 13 '22 at 15:15
  • 1
    What would really help here is some ddl (create table statements), sample data (insert statements) and then a text (not image) list of the desired output. – Sean Lange May 13 '22 at 15:17
  • 1
    While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example): (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in the #1 above. (4) Your SQL Server version (SELECT @@version;). – Yitzhak Khabinsky May 13 '22 at 15:27
  • @SeanLange Thanks for the heads up. I edited the post with what you requested. Hope that helps, and thanks for your time. – SamTheSandman May 13 '22 at 15:41
  • What is your 1 (specific researched non-duplicate) question. If you have syntax error, what is all that other stuff doing here? (Rhetorical.) What does the grammar & many many intro sites & Q&A here say? PS Saying you searched & listing links "does not show any research effort". Quote/paraphrase with credit & relate to your post. PS [How to create a MySQL hierarchical recursive query](https://stackoverflow.com/q/20215744/3404097) – philipxy May 13 '22 at 15:54
  • A [mre] includes cut & paste & runnable code; example input with desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. For errors that includes the least code you can give that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) For SQL include DDL & tabular initialization code. When you get a result you don't expect, pause your overall goal, chop to the 1st subexpression with unexpected result & say what you expected & why, justified by documentation. [ask] [Help] – philipxy May 13 '22 at 15:56
  • Comma was never "replaced", it continues to mean cross join. It has lower precedence than keyword joins so don't mix the two, it confuses readers. Other than that the main problem with using them is people telling you not to use them. – philipxy May 13 '22 at 16:02
  • @philipxy true the antiquated delimited list wasn't replaced, poor word choice on my part. They are however more difficult to read and error prone. – Sean Lange May 13 '22 at 19:12

1 Answers1

-1

Please try the following conceptual example.

SQL

-- DDL and sample data population, start
DECLARE @tbl table (
    idGeo INT IDENTITY PRIMARY KEY,
    GEO   VARCHAR(64),
    PARENTID INT
);
INSERT INTO @tbl (GEO, PARENTID) VALUES 
(   'EMEA',    NULL),
(   'France',  1),
(   'Normandy',   2),
(   'Germany', 1),
(   'Gascony',  2),
(   'Americas',    NULL),
(   'US',  6);
-- DDL and sample data population, end

--SELECT * FROM @tbl;

WITH cte AS 
(
    -- Anchor query
    SELECT idGEO, GEO, ParentID, 1 AS [Level]
        , CAST('/' + GEO AS VARCHAR(1000)) AS XPath
    FROM @tbl
    WHERE ParentID IS NULL
    UNION ALL
    -- Recursive query
    SELECT t.idGEO, t.GEO, t.ParentID, cte.[Level] + 1 AS [Level]
        , CAST(cte.[XPath] + '/' +  t.GEO AS VARCHAR(1000)) AS [XPath]
    FROM @tbl AS t
        INNER JOIN cte ON t.ParentID = cte.idGEO
    WHERE t.ParentID IS NOT NULL 
)
SELECT idGEO, GEO
    , REPLICATE('  ',[Level]-1) + GEO AS GEOHierarchy
    , [level]
    , [XPath]
FROM cte
ORDER BY XPath;

Output enter image description here

Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/3404097) [Why are images of text, code and mathematical expressions discouraged?](https://meta.stackexchange.com/q/320052/266284) – philipxy May 13 '22 at 17:46