Question : Get Top most parent id

Hi

I have a recursive table that I use to populate a treeview control.

What I need is a routine that from any given tree node, will give me the ID of the first parent node in the tree. ie  I want the top node that has the parent ID = null, (as its the top)

The selected tree node can be anywhere down the tree hierarchy.

Andy

Answer : Get Top most parent id

Try this

CREATE PROCEDURE [dbo].[uspGetParentNodeId]
   @Id   INT
AS
BEGIN
   SET NOCOUNT ON
   
   DECLARE @ParentId INT

   SELECT @ParentId = ParentId
   FROM tbYourTable
   WHERE Id = @Id
   
   IF @Id IS NULL
   BEGIN
         RETURN @Id
   END
   ELSE
   BEGIN
         EXECUTE uspGetParentNodeId @ParentId
   END
END
GO
Random Solutions  
 
programming4us programming4us