mysql分割字符串

項目有經過一批ID去過濾結果的需求,由於這個ID是從其餘平臺拉下來的excel,爲了不加引號逗號的麻煩,在mysql存儲過程裏面拼接。在此作個記錄。不少地方用得上。
1.經過某個字符,分割字符串的函數。輸入分別爲f_string(待分割字符串),f_delimiter(分割字符),f_order(取的字符串的index)mysql

DELIMITER $$

USE `money`$$

DROP FUNCTION IF EXISTS `F_SPLIT_STRING`$$

CREATE DEFINER=`root`@`%` FUNCTION `F_SPLIT_STRING`(
f_string VARCHAR(1000),f_delimiter VARCHAR(5),f_order INT) RETURNS VARCHAR(255) CHARSET utf8
BEGIN
  DECLARE result VARCHAR(255) DEFAULT '';
  SET result = REVERSE(SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(f_string,f_delimiter,f_order)),f_delimiter,1));
  RETURN result;
END$$

DELIMITER ;

2.要循環取分割出來的字符串就得知道分割出來多少個字符串sql

SELECT LENGTH(APPSFLYERID) - LENGTH(REPLACE(APPSFLYERID, '\n', '')) + 1 INTO @APPSFLYERID_CNT;

3.處理一串以n分割的字符串,把它們加上分號和逗號。
'1518393292248-9957634
1518404097075-8568716
1518392385006-9013409'轉換成
'1518393292248-9957634','1518404097075-8568716','1518392385006-9013409'函數

DELIMITER $$
USE `money`$$

DROP PROCEDURE IF EXISTS `P_GET_ROI_BY_APPFLYER_ID`$$

CREATE DEFINER=`root`@`%` PROCEDURE `P_GET_ROI_BY_APPFLYER_ID`(IN STAT_DATE VARCHAR(32),IN DAY_CNT INT,IN APPSFLYERID MEDIUMTEXT)
BEGIN
    SET @APPSFLYERID_STR = "";
    SET @TEMP_ID = "";
    SELECT LENGTH(APPSFLYERID) - LENGTH(REPLACE(APPSFLYERID, '\n', '')) + 1 INTO @APPSFLYERID_CNT;
    
    SET @i = 1;
    WHILE @i <= @APPSFLYERID_CNT DO
    SELECT F_SPLIT_STRING(APPSFLYERID,"\n",@i) INTO @TEMP_ID;
    IF @i = 1 THEN
    SET @APPSFLYERID_STR = CONCAT("'",@TEMP_ID,"'");
    ELSE
    SET @APPSFLYERID_STR = CONCAT(@APPSFLYERID_STR,",'",@TEMP_ID,"'");
    END IF; 
    SET @i = @i + 1;
    END WHILE;
    SELECT   @APPSFLYERID_STR;
END$$

DELIMITER ;
相關文章
相關標籤/搜索