目前我正在寻找一个"剪切字符串"varchar的解决方案。
我有一个游标,它运行在我从SQL语句中获得的所有行中。在这些行中的每一行都包含一个"#",我想剪切并插入到另一个表中。
但是我怎样才能去掉"#"和后面的字符呢
我考虑过拆分,但没有找到在MySQL中如何做到这一点的解决方案。
我希望你能帮助我
假设您有一个类似first #second third
的字符串,您可以使用MySQL的字符串函数来提取second
:
SUBSTRING(SUBSTRING(col, INSTR(col, '#') + 1),
1,
INSTR(SUBSTRING(col, INSTR(col, '#') + 1), ' ') - 1)
这假设只有一个散列符号(#
),并且要提取的字符串末尾的delimeter是一个空格。
以下是实现的函数示例
delimiter //
CREATE DEFINER=`root`@`localhost` FUNCTION `cut`(`instring` varchar(255))
RETURNS varchar(255) CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin
declare tempstring varchar(100);
declare outstring varchar(100);
declare checkit int;
declare firsthashpos int;
declare tempid int;
set tempstring = ltrim(rtrim(instring));
set checkit = 0;
if instr(tempstring,'#') then set firsthashpos = instr(tempstring,'#'); end if;
looper: while tempstring is not null and instr(tempstring,'#') > 0 do
set outstring = reverse(substring(reverse(tempstring),1,instr(reverse(tempstring),'#')));
set tempstring = replace(tempstring,reverse(substring(reverse(tempstring),1,instr(reverse(tempstring),'#'))),'');
insert into b (address) values (outstring);
end while;
return concat(tempstring);
end//
delimiter ;
给定这个
select * from a;
+------+---------------------+
| id | address |
+------+---------------------+
| 1 | 13 #ont 12#45 st |
| 2 | 13 #ont 12345 st |
| 3 | 13 #ont 12#45 45678 |
| 4 | 56789 #ont 12#45 st |
+------+---------------------+
的结果
select id,address,cut(address)
from a
where instr(address,'#') > 0;
b 中的结果
select * from b;
+----+---------------+
| id | address |
+----+---------------+
| 1 | #45 st |
| 2 | #ont 12 |
| 3 | #ont 12345 st |
| 4 | #45 45678 |
| 5 | #ont 12 |
| 6 | #45 st |
| 7 | #ont 12 |
+----+---------------+
函数(outstring)的返回值包含删除#s后的位之后剩下的内容。希望函数中的字符串操作是不言自明的。