这是完成这项工作的 mysql 程序(用 mysql 5.5 测试):
DROP PROCEDURE if exists split_sentence;
delimiter $$
CREATE PROCEDURE split_sentence(sentence varchar(255), delimiter VARCHAR(50), out result_wordcount INTEGER)
BEGIN
DECLARE last_position INTEGER;
DECLARE position INTEGER;
DROP TABLE IF EXISTS tmp_split_sentence;
CREATE TEMPORARY TABLE tmp_split_sentence (word varchar(255));
set last_position = 1;
set position = instr(sentence, delimiter);
-- select position;
WHILE position > 0 DO
-- select concat('found: ', substring(sentence, last_position, position-last_position));
INSERT INTO tmp_split_sentence (word) VALUES(substring(sentence, last_position, position-last_position));
set last_position = position+length(delimiter);
set position = locate(delimiter, sentence, last_position);
-- select concat('position: ', position);
END WHILE;
-- wrap up to the end of the sentence
if last_position < length(sentence) then
INSERT INTO tmp_split_sentence (word) VALUES(substring(sentence, last_position, length(sentence)-last_position+1));
end if;
SELECT count(*) into result_wordcount from tmp_split_sentence;
END$$
delimiter ;
DROP TABLE IF EXISTS tmp_sentence;
CREATE TEMPORARY TABLE tmp_sentence (word varchar(255));
call split_sentence('this is a sentence', ' ', @result_wordcount);
INSERT INTO tmp_sentence select * from tmp_split_sentence;
call split_sentence('sentence galore', ' ', @result_wordcount);
INSERT INTO tmp_sentence select * from tmp_split_sentence;
select * from tmp_sentence;
结果:
this
is
a
sentence
sentence
galore
请注意,这句话出现了多次,应该在问题中修正:)。