You are here: Re: How do I write a query to get the path from ancestor to node in a tree? « MsSQL Server « IT news, forums, messages
Re: How do I write a query to get the path from ancestor to node in a tree?

Posted by Jens on 11/09/04 11:26

Try that:

IF OBJECT_ID('Tree') IS NOT NULL
DROP Table Tree

CREATE TABLE Tree
(
Parent INT,
Child INT
)

INSERT INTO Tree
SELECT 100,200


INSERT INTO Tree
SELECT 100,300


INSERT INTO Tree
SELECT 100,400


INSERT INTO Tree
SELECT 400,500


INSERT INTO Tree
SELECT 500,1000

DROP FUNCTION getHierarchy

GO

CREATE FUNCTION getHierarchy
(
@child INT
)
RETURNS @Hierarchy TABLE
(
Path INT
)
AS
BEGIN

IF NOT EXISTS (SELECT * from Tree where child = @child)
BEGIN
INSERT INTO @Hierarchy
SELECT NULL
SET @child = NULL
END

WHILE (@Child IS NOT NULL OR LEN(@Child) = 0)
BEGIN
INSERT INTO @Hierarchy
SELECT @Child

SELECT @Child = Parent from Tree where child = @child
IF @@ROWCOUNT = 0 SET @Child = NULL
END

RETURN
END

GO

Select * from dbo.getHierarchy(500)

HTH, Jens Suesmeyer

---
http://www.sqlserver2005.de
---

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация