mysql写一个按逗号拆分字符串为一列的存储过程,字符串长度不做限制,方便日后随时调用
时间: 2024-05-13 20:17:31 浏览: 115
Mysql通过存储过程分割字符串为数组
下面是一个简单的 MySQL 存储过程,它接受一个字符串参数,并将其按逗号分隔为单独的列。你可以随时调用这个存储过程。
```
CREATE PROCEDURE `split_string`(IN str VARCHAR(255))
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE value VARCHAR(255);
DECLARE cur CURSOR FOR SELECT SUBSTRING_INDEX(str, ',', 1) AS value, CONCAT(SUBSTRING(str, LENGTH(SUBSTRING_INDEX(str, ',', 1))+2), ',') AS str;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_table (value VARCHAR(255));
OPEN cur;
read_loop: LOOP
FETCH cur INTO value, str;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO temp_table (value) VALUES (TRIM(value));
IF LENGTH(str) = 0 THEN
LEAVE read_loop;
END IF;
END LOOP;
CLOSE cur;
SELECT * FROM temp_table;
DROP TEMPORARY TABLE IF EXISTS temp_table;
END
```
使用示例:
```
CALL split_string('apple,banana,orange');
```
输出结果:
```
+--------+
| value |
+--------+
| apple |
| banana |
| orange |
+--------+
```
阅读全文