首页 > 技术文章 > sql 根据子级ID获取所有父级

fannyatg 2019-04-11 14:24 原文

 

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

推荐阅读