During converting Oracle statements into SQL Server T-SQL, there seems no direct equivalent of Oracle PL/SQL CONNECT BY PRIOR ... START WITH statement in SQL Server. The SQL standard way to implement recursive queries, is the WITH
clause (recursive CTE).
Oracle PL/SQL example:
select UserID, FirstName, LastName
from Users
WHERE UserTypeID = 5
CONNECT BY PRIOR UserID = ParentID START WITH UserID = 2320
ORDER BY LastName
SQL Server T-SQL code:
WITH N (Userid, FirstName, LastName, UserTypeID)
AS
(
SELECT UserID, FirstName, LastName
FROM Users
WHERE Userid = 2320
UNION ALL
SELECT np.UserID, np.FirstName, np.LastName, np.UserTypeID
FROM Users AS np JOIN N ON N.UserID = np.ParentID
)
SELECT Userid, FirstName, LastName
FROM N
WHERE UserTypeID = 5
ORDER BY Lastname
Be careful with the CONNECT BY ... PRIOR statement, if in Oracle:
CONNECT BY UserID = PRIOR ParentID START WITH UserID = 2320 instead of
CONNECT BY PRIOR UserID = ParentID START WITH UserID = 2320
Then in SQL should be:
WITH N (Userid, FirstName, LastName, UserTypeID, ParentID)
AS
(
SELECT UserID, FirstName, LastName, UserTypeID, ParentID
FROM Users
WHERE Userid = 2320
UNION ALL
SELECT np.UserID, np.FirstName, np.LastName, np.UserTypeID, np.ParentID
FROM Users AS np JOIN N ON np.UserID = N.ParentID
)
SELECT Userid, FirstName, LastName
FROM N
WHERE UserTypeID = 5
ORDER BY Lastname
For more info about using recursive queries with WITH, please refer to here.