Standard alternative to CONNECT BY?
Asked Answered
C

2

8

I'm trying to convert some Oracle SQL queries to work with (in theory) any SQL database. Some of the queries are hierarchical in nature and are written using CONNECT BY.

Is there a standard SQL alternative to Oracle's START WITH...CONNECT BY syntax? Or is there some recommended process I should follow to convert the hierarchical queries?

Cranford answered 3/11, 2009 at 17:21 Comment(1)
There isn't any ANSI hierarchical query syntax that I'm aware of - it's different between SQL Server, MySQL, & Postgres at least.Boorish
M
8

In Oracle 11gR2 they support recursion in Common Table Expressions (what most Oracle people know as sub-querying factoring, i.e. the WITH clause). As this is the ANSI way of doing things it ought to be more portable.

Tom Kyte writes about Recursive Subquery Factoring in the November 09 edition of Oracle magazine.

Maeda answered 3/11, 2009 at 17:56 Comment(1)
AFAIK: SQL Server, Oracle and DB2 are the only databases supporting the WITH clause. I don't know if DB2's version supports recursion...Boorish
P
2

If you need hierarchical queries against databases that don't support Recursive Subquery Factoring (see APC's answer), one very low-tech alternative is to encode the hierarchy into a separate key. Of course this will only work if you can control the table update process and rewrite the key following parent updates.

For example:

FLAT_HIER_ID  NODE_ID   PARENT_NODE_ID
~N1           N1
~N1~N2        N2        N1
~N1~N2~N3     N3        N2
~N1~N2~N4     N4        N2

Not very elegant, but it gives you a route for querying.

Another (probably better) option is to use the "Nested Set Model" method. This is the method used in Fogbugz for handling subcase querying in MSSQL, MySQL, and MS Access.

The model is explained at:

http://www.developersdex.com/gurus/articles/112.asp

The use of the method in Fogbugz is described at:

http://www.fogcreek.com/FogBugz/blog/post/Subcases-and-Hierarchy.aspx

Pinguid answered 4/11, 2009 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.