mysql将查出的字符串拆分_Mysql拆分字符串查询

DELIMITER $$

DROP FUNCTION IF EXISTS `tms1`.`GetClassName` $$

CREATE FUNCTION `GetClassName`(f_string VARCHAR(15000)) RETURNS varchar(15000)

BEGIN

/* 判断字符串包含,的第一个位置*/

DECLARE THE_CNT INT(15) DEFAULT 1;

/* 班级编号*/

declare classId varchar(20) default '';

/* 返回的班级名称*/

DECLARE result varchar(15000) DEFAULT null;

/* 班级名称*/

DECLARE className varchar(50) DEFAULT '';

/* 字符串包含,的第一个位置*/

set THE_CNT = LOCATE(',',f_string);

/* 判断字符串包含,的第一个位置是否存在*/

while (THE_CNT >= 0) do

/* ,位置不存在的场合*/

if THE_CNT = 0 then

/* 班级编号的设置*/

set classId = f_string;

else

/* 字符串中获得班级编号*/

set classId = SUBSTRING_INDEX(SUBSTRING_INDEX(f_string, ',', 1), ',', -1);

end if ;

/* 根据班级编号获得班级名称*/

select (select name from class where id = classId) into className;

/* 返回班级编号的字符串为空的场合*/

if result is null then

/* 根据编号没有查询到班级名称的场合*/

if className is null then

/* 设置班级名称为空*/

set className = ' ';

end if;

/* 班级名称追加到字符串*/

set result = className;

else

/* 根据编号没有查询到班级名称的场合*/

if className is null then

/* 设置班级名称为空*/

set className = '  ';

end if;

/* 班级名称追加到字符串*/

set result = CONCAT(result,',',className);

end if;

/* ,位置不存在的场合*/

if THE_CNT = 0 then

/* 返回结果集*/

return result;

end if;

/* 截取传入的字符串*/

set f_string = right(f_string,length(f_string) - THE_CNT);

/* 字符串包含,的第一个位置*/

set THE_CNT = LOCATE(',',f_string);

/* 结束遍历*/

end while;

/* 返回结果集*/

return result;

END $$

DELIMITER ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值