views:

5865

answers:

3

I would like to get the functionality of CONNECT BY PRIOR of ORACLE in SQL SERVER 2000/2005/2008?

Please help me

+8  A: 

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (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:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

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):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

Alex Martelli
Please explain with an example.E.g. Take some countries and statesLikeIndia --State1 -- State2Australia --AusState1 --AusStae2I am looking for the exact query
priyanka.sarkar
The example I pointed to, at URL http://www.ibm.com/developerworks/db2/library/techarticle/dm-0510rielau/ , does give the exact query -- copying it here seems pointless when you can just click on the link!-)
Alex Martelli
+1  A: 

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

Joel Coehoorn
Please explain with an example.E.g. Take some countries and statesLikeIndia --State1 -- State2Australia --AusState1 --AusStae2
priyanka.sarkar
+1  A: 

In SQL Server universe these are called Recursive CTEs. The following explains them:

http://blogs.msdn.com/craigfr/archive/2007/11/07/recursive-ctes-continued.aspx

AlexKuznetsov