How can I get the functionality of CONNECT BY PRIOR of Oracle in SQL Server 2000/2005/2008?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the
WITHclause. See this article for one example of translating aCONNECT BYinto aWITH(technically a recursive CTE) — the example is for DB2 but I believe it will work on SQL Server as well.Edit: apparently the original querant requires a specific example, here’s one from the IBM site whose URL I already gave. Given a table:
where
mgridreferences an employee’s manager’sempid, the task is, get the names of everybody who reports directly or indirectly toJoan. In Oracle, that’s a simpleCONNECT:In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that’s worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
Oracle’s
START WITHclause becomes the first nestedSELECT, the base case of the recursion, to beUNIONed with the recursive part which is just anotherSELECT.SQL Server’s specific flavor of
WITHis of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.