String x "3_SJ454FH";
我想将'3'(在_之前)存储在mysql的另一列中,并将'SJ454FH'(在_之后)存储在另一列中。我已经在存储过程中尝试过substring_index函数,但是没有起作用。那么,有什么方法可以在存储过程中存储这样的价值??
CREATE DEFINER=`root`@`localhost` 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
输出:
id|c1
-----------
1 |3
-----------
2 |SJ454FH
-----------
我已经尝试过这段代码,但是它存储在下一行。
答案 0 :(得分:0)
您可以将以下查询的逻辑与INTO结合使用,以所需的值填充两个变量,然后在单独的调用中将其插入。
SELECT LEFT("3_SJ454FH", INSTR("3_SJ454FH", "_")-1) AS Prefix,
MID("3_SJ454FH", INSTR("3_SJ454FH", "_")+1, LENGTH("3_SJ454FH")) AS Tail