Mysql - 如何在存储过程中拆分文本变量

时间:2014-06-05 11:48:38

标签: mysql stored-procedures

我有一个MySQL变量,如下所示。

DECLARE str TEXT DEFAULT '2014-01-02 13:00:00|2014-02-04 12:59:59@0@2014-02-04 13:00:00|2014-03-04 12:59:59@0@2014-03-04 13:00:00|2014-04-02 13:59:59@0@2014-04-02 14:00:00|2014-05-02 14:59:59@0@2014-05-02 15:00:00|2014-06-03 14:59:59';  

我想首先使用分隔符@0@来破坏整个字符串,然后从结果中使用分隔符|来破坏字符串。

我尝试了MySQL split_str功能,但我无法做到 它给了我错误split_str does not exist 请提出其他一些方法。

1 个答案:

答案 0 :(得分:0)

最后,我使用以下程序解决了我的问题。

我可以使用临时表和程序解决它。我不再使用mysql变量了。我们可以调用以下程序....

 CALL SplitString('2014-01-02 13:00:00|2014-02-04 12:59:59@0@2014-02-04 13:00:00|2014-03-04 12:59:59@0@2014-03-04 13:00:00|2014-04-02 13:59:59@0@2014-04-02 14:00:00|2014-05-02 14:59:59@0@2014-05-02 15:00:00|2014-06-03 14:59:59', '@0@', 'tblindex');

这里tblindex是我用过的临时表。

我的程序如下......

 DELIMITER $$

 DROP PROCEDURE IF EXISTS `SplitString`$$

 CREATE PROCEDURE `SplitString`( IN input TEXT,IN delm VARCHAR(10),tblnm varchar(50))
 BEGIN
     DECLARE cur_position INT DEFAULT 1 ;
     DECLARE remainder TEXT;
     DECLARE cur_string VARCHAR(1000);
     DECLARE delm_length TINYINT UNSIGNED;
     set @sql_drop = concat("DROP TABLE IF EXISTS ",tblnm); 
     prepare st_drop from @sql_drop;
     execute st_drop; 
     set @sql_create = concat("CREATE TEMPORARY TABLE ",tblnm," (value VARCHAR(2000) NOT NULL ) ENGINE=MEMORY;");
     prepare st_create from @sql_create;
     execute st_create; 
     SET remainder = input;
     SET delm_length = CHAR_LENGTH(delm);
     WHILE CHAR_LENGTH(remainder) > 0 AND cur_position > 0 
     DO
         SET cur_position = INSTR(remainder, delm);
         IF cur_position = 0 THEN
             SET cur_string = remainder;
         ELSE
             SET cur_string = LEFT(remainder, cur_position - 1);
         END IF;
         -- select cur_string;
         IF TRIM(cur_string) != '' THEN
             set @sql_insert = concat("INSERT INTO ",tblnm," VALUES ('",cur_string,"');");
             prepare st_insert from @sql_insert;
             execute st_insert; 
         END IF;
         SET remainder = SUBSTRING(remainder, cur_position + delm_length);
     END WHILE;

 END$$

 DELIMITER ;