CREATE function [dbo].[getGroupPath](@groupId int) returns nvarchar(2000) as begin declare @path nvarchar(2000)='/'; with cr as ( select * from FAQGroup where Id=@groupId union all select b.* from cr a join FAQGroup b on a.ParentId=b.id ) select @path=@path+cast(ID as nvarchar) +'/' from cr order by id return left(@path,len(@path))