sql 根据子级ID获取所有父级

 

CREATE FUNCTION [dbo].[f_GetParentCode](@id int)
  RETURNS @re TABLE(id int,pid int,level int)
  AS
  begin
  declare @level int
  set @level = 1
  declare @pid int
  select @pid = ParentCode from T_GWZJ_CityMapping where HCityCode = @id
  insert @re
  select HCityCode,ParentCode,@level from T_GWZJ_CityMapping where HCityCode = @id
  set @level = @level + 1
  insert @re
  select HCityCode,ParentCode,@level from T_GWZJ_CityMapping where HCityCode = @pid
  while @@rowcount > 0  
  begin
  set @level = @level + 1
  select @pid = ParentCode from T_GWZJ_CityMapping where HCityCode = @pid
  insert @re
  select HCityCode,ParentCode,@level from T_GWZJ_CityMapping where HCityCode = @pid
  end
  return
  end

GO

posted @ 2019-04-11 14:24  fanny_atg  阅读(388)  评论(0编辑  收藏  举报