mysql 分割后循环_拆分字符串并循环遍历MySql过程中的值

你需要对字符串操作更加小心.您不能使用REPLACE(),因为这将替换多次出现,如果逗号分隔列表中的一个元素是另一个元素的子字符串,则会破坏您的数据.

INSERT() string function对此更好,不要与用于插入表的INSERT语句混淆.

DELIMITER $$

DROP PROCEDURE IF EXISTS `insert_csv` $$

CREATE PROCEDURE `insert_csv`(_list MEDIUMTEXT)

BEGIN

DECLARE _next TEXT DEFAULT NULL;

DECLARE _nextlen INT DEFAULT NULL;

DECLARE _value TEXT DEFAULT NULL;

iterator:

LOOP

-- exit the loop if the list seems empty or was null;

-- this extra caution is necessary to avoid an endless loop in the proc.

IF LENGTH(TRIM(_list)) = 0 OR _list IS NULL THEN

LEAVE iterator;

END IF;

-- capture the next value from the list

SET _next = SUBSTRING_INDEX(_list,',',1);

-- save the length of the captured value; we will need to remove this

-- many characters + 1 from the beginning of the string

-- before the next iteration

SET _nextlen = LENGTH(_next);

-- trim the value of leading and trailing spaces, in case of sloppy CSV strings

SET _value = TRIM(_next);

-- insert the extracted value into the target table

INSERT INTO t1 (c1) VALUES (_value);

-- rewrite the original string using the `INSERT()` string function,

-- args are original string, start position, how many characters to remove,

-- and what to "insert" in their place (in this case, we "insert"

-- an empty string, which removes _nextlen + 1 characters)

SET _list = INSERT(_list,1,_nextlen + 1,'');

END LOOP;

END $$

DELIMITER ;

接下来,测试表:

CREATE TABLE `t1` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`c1` varchar(64) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

新表是空的.

mysql> SELECT * FROM t1;

Empty set (0.00 sec)

打电话给程序.

mysql> CALL insert_csv('foo,bar,buzz,fizz');

Query OK, 1 row affected (0.00 sec)

请注意,“受影响的1行”并不代表您的期望.它指的是我们做的最后一个插入.由于我们一次插入一行,如果过程插入至少一行,则总是得到行数1;如果程序什么都不插入,你将受到0行的影响.

它有用吗?

mysql> SELECT * FROM t1;

+----+------+

| id | c1 |

+----+------+

| 1 | foo |

| 2 | bar |

| 3 | buzz |

| 4 | fizz |

+----+------+

4 rows in set (0.00 sec)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值