別人問的一個需求:mysql
drop function if exists getName; create FUNCTION getName(v_code int) returns varchar(10) begin declare v_name varchar(10); declare v_name2 varchar(10); set v_name=''; set v_name2=''; repeat select `name`,`parent_code` into v_name,v_code from material_type where `code` = v_code limit 1; set v_name2 = concat_ws('/',v_name,v_name2); until v_code = 0 end repeat; return v_name2; end;
而後以下查詢操做:sql
select code,name,parent_code,getName(code) from material_type;
結果顯示以下:數據庫
注意:這裏的頂層跟節點的code必須是0函數