I have a table called tblmodules which has 3 columns: moduleid,name,parent_id. The column parent_id takes values of other modules. ex:
Moduleid Name Parentid
-------- ----- --------
1 grandparent Null
2 parent 1
3 child 2
I want a stored procedure that takes the parent’s Id and Name of a child giving a level. So i develop the following.
@moduleid bigint,
@level int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @parentid bigint
declare @name nvarchar(100)
set @parentid = (select parentid from tblModules where ModuleId = @moduleid)
declare @counter int
set @counter = 1
while @counter < @level
begin
set @parentid = (select parentid from tblModules where ModuleId = @parentid)
set @name = (select Name from tblModules where ModuleId = @parentid)
set @counter = @counter + 1
end
select @parentid AS ID
select @name as Name
end
The procedure works fine and gets the correct Id of the parent, but the name remains the same as the child. For ex i am executing it giving the values @moduleid: 3 and @level:2.
I am getting result ID: 1 which is correct but Name: child instead of Grandparent. Any help?
In my script I use CTE for level finding Modules that will join with their ParentLevel(@level)
Demo on SQL Fiddle