|
sql
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
SQL 2008: How to recursive Procedure for parentNavigation?
how can I do a recursive Procedure in SQL 2008 to get all parentNavigation Nodes for this example? navigaionID parentNavigationID Level ------------------------------------------ 1 0 0 2 0 0 3 0 0 4 2 1 5 0 0 6 4 2 7 6 3 I just want a function where I enter the navigationID and then get all partenNavigationIDs like this MyProcedureGetAllParentNodes @navigationID=7 Result: navigaionID Level -------------------- 6 3 4 2 2 1 Many, many thanks in advance for any help! Andreas The following will give you the requested result set:
CREATE TABLE Navigation ( navigationID INT PRIMARY KEY, parentNavigationID INT, Level INT); INSERT INTO Navigation VALUES (1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 2, 1), (5, 0, 0), (6, 4, 2), (7, 6, 3); GO CREATE PROCEDURE MyProcedureGetAllParentNodes @navigationID INT AS WITH NavigationCTE AS (SELECT navigationID, parentNavigationID, Level FROM Navigation WHERE navigationID = @navigationID UNION ALL SELECT N.navigationID, N.parentNavigationID, N.Level FROM Navigation AS N JOIN NavigationCTE AS C ON N.navigationID = C.parentNavigationID WHERE N.parentNavigationID <> 0) SELECT parentNavigationID AS navigationID, Level FROM NavigationCTE; GO EXEC MyProcedureGetAllParentNodes @navigationID = 7; /* Results: navigationID Level ------------ ----------- 6 3 4 2 2 1 */ Hi Plamen,
thank you very much! It helped me. Regards Andres Show quoteHide quote "Plamen Ratchev" <Pla***@SQLStudio.com> schrieb im Newsbeitrag news:C8adneQ_0MltTN7UnZ2dnUVZ_sfinZ2d@speakeasy.net... > The following will give you the requested result set: > > CREATE TABLE Navigation ( > navigationID INT PRIMARY KEY, > parentNavigationID INT, > Level INT); > > INSERT INTO Navigation VALUES > (1, 0, 0), > (2, 0, 0), > (3, 0, 0), > (4, 2, 1), > (5, 0, 0), > (6, 4, 2), > (7, 6, 3); > > GO > > CREATE PROCEDURE MyProcedureGetAllParentNodes > @navigationID INT > AS > WITH NavigationCTE > AS > (SELECT navigationID, parentNavigationID, Level > FROM Navigation > WHERE navigationID = @navigationID > UNION ALL > SELECT N.navigationID, N.parentNavigationID, N.Level > FROM Navigation AS N > JOIN NavigationCTE AS C > ON N.navigationID = C.parentNavigationID > WHERE N.parentNavigationID <> 0) > SELECT parentNavigationID AS navigationID, Level > FROM NavigationCTE; > > GO > > EXEC MyProcedureGetAllParentNodes @navigationID = 7; > > /* > > Results: > > navigationID Level > ------------ ----------- > 6 3 > 4 2 > 2 1 > > */ > > > -- > Plamen Ratchev > http://www.SQLStudio.com
Other interesting topics
High CPU Use
text to number <--SQL rookie here Options dbcc shrinkfile SQL Server 2008 - remote connection problems sql server hung Command to quit executing query through script Pending Reboot Requirement html encoding How ca I Read the select Statement of a view ? Commands SQL Server 2000 EM to SQL Server 2005 SSMS |
|||||||||||||||||||||||