Mysql儲存過程中字串分割

2021-07-25 06:16:38 字數 2420 閱讀 3453

今在專案中碰到了要把字串分割,記錄下來,以後可能還用的到

首先想上我的儲存過程**

delimiter $$

use `bplate`$$

drop procedure if exists `lp_plate_insertplateinfo`$$

create definer=`root`@`localhost` procedure `lp_plate_insertplateinfo`(

plate_user int,

plate_title varchar(60) ,

plate_type int,

plate_img varchar(500),

plate_content mediumtext,

plate_sku_name varchar(60),

plate_sku_price varchar(60)

)begin

declare i int default 0;

set @sql1=concat("insert into bp_plate(`plate_user`,`plate_title`,`plate_type`,`plate_img`,`plate_sales`,`plate_content`,`plate_level`,`plate_time`,`plate_state`) value(",plate_user,",'",plate_title,"',",plate_type,",'",plate_img,"',",0,",'",plate_content,"',0,now(),1)");

prepare sql1 from @sql1;

execute sql1;

set @plate_id='';

select last_insert_id() into @plate_id from bp_plate limit 0,1;

set @arraylength=1+(length(plate_sku_name) - length(replace(plate_sku_name,',','')));

while i<@arraylength

doset i=i+1;

set @result = reverse(substring_index(reverse(substring_index(plate_sku_name,',',i)),',',1));

set @resultprice = reverse(substring_index(reverse(substring_index(plate_sku_price,',',i)),',',1));

insert into bp_plate_sku(`plate_id`,`sku_name`,`sku_price`,`sku_time`,`sku_state`) value(@plate_id,@result,@resultprice,now(),1);

end while;

end$$

delimiter ;

這是我整個儲存過程,分割的是傳進來的

plate_sku_name varchar(60),

plate_sku_price varchar(60)

變數,注意型別不能是int,不然不能分割

然後只要分割方法在於

set @arraylength=1+(length(plate_sku_name) - length(replace(plate_sku_name,',','')));		

while i<@arraylength

doset i=i+1;

set @result = reverse(substring_index(reverse(substring_index(plate_sku_name,',',i)),',',1));

set @resultprice = reverse(substring_index(reverse(substring_index(plate_sku_price,',',i)),',',1));

insert into bp_plate_sku(`plate_id`,`sku_name`,`sku_price`,`sku_time`,`sku_state`) value(@plate_id,@result,@resultprice,now(),1);

end while;

@arraylength獲取要分割字串根據符號分割後的陣列長度

之後便是乙個while迴圈

中間用

reverse(substring_index(reverse(substring_index(plate_sku_name,',',i)),',',1));
方式來分割

裡面的『,』是根據要分割的字元,plate_sku_name是要分割的字串,變數i要從1開始

之後便能分割了

mysql 字串分割儲存過程

drop procedure if exists splitstr create procedure splitstr in str varchar 255 out substr varchar 2000 out idstr varchar 100 begin declare index var v...

MySql分割字串 儲存過程

mysql沒有表變數,通過函式無法返回表。參考 delimiter use 資料庫 drop procedure if exists split create definer sa scmone procedure split in string varchar 300 begin 求分割符號 的位...

儲存過程中拼接字串

1.將查詢資料插入臨時表 最開始我這麼寫的 declare sql varchar max set sql select into tmp from tb exec sql select from tmp 報錯物件名 tmp 無效 可以改成這樣子 create table tmp declare s...