POSTGRESQL与MYSQL实现分割字符串的方法对比

WBOY
發布: 2016-06-07 15:23:19
原創
1293 人瀏覽過

实现分割字符串。 DELIMITER $$ CREATE DEFINER=`root`@`%` FUNCTION `func_get_split_string_total`( f_string VARCHAR(1000),f_delimiter VARCHAR(5) ) RETURNS INT(11) BEGIN -- Get the total number of given string. RETURN 1+(LENGTH(f_string) - LENG

实现分割字符串。
DELIMITER $$ CREATE DEFINER=`root`@`%` FUNCTION `func_get_split_string_total`( f_string VARCHAR(1000),f_delimiter VARCHAR(5) ) RETURNS INT(11) BEGIN -- Get the total number of given string. RETURN 1+(LENGTH(f_string) - LENGTH(REPLACE(f_string,f_delimiter,''))); END$$ DELIMITER ;
DELIMITER $$ CREATE DEFINER=`root`@`%` FUNCTION `func_get_split_string`( f_string VARCHAR(1000),f_delimiter VARCHAR(5),f_order INT) RETURNS VARCHAR(255) CHARSET utf8 BEGIN -- Get the separated number of given string. 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 ;
登入後複製
DELIMITER $$ CREATE PROCEDURE `sp_print_result`( IN f_string VARCHAR(1000),IN f_delimiter VARCHAR(5) ) BEGIN -- Get the separated string. DECLARE cnt INT DEFAULT 0; DECLARE i INT DEFAULT 0; SET cnt = func_get_split_string_total(f_string,f_delimiter); DROP TABLE IF EXISTS tmp_print; CREATE TEMPORARY TABLE tmp_print (v_text varchar(200) NOT NULL); WHILE i 
<pre class="brush:php;toolbar:false">
我们来执行: 
登入後複製
CALL sp_print_result(&#39;love,you,hate,number&#39;,&#39;,&#39;);
query result
v_text 
love 
you 
hate 
number 
登入後複製
create or replace function split_to_string( IN f_string text, IN f_delimiter varchar(10) ) returns setof text as $ytt$ declare cnt int; declare i int; declare v_result text; begin i := 1; cnt := length(f_string) - length(replace(f_string,f_delimiter,''))+1; while i <= cnt loop v_result := split_part(f_string,f_delimiter,i); return next v_result; i := i + 1; end loop; end; $ytt$ language plpgsql; 结果: t_girl=# select split_to_string('love,you,hate,number',',') as result; result -------- love you hate number (4 rows)
t_girl=# SELECT ytt FROM regexp_split_to_table(&#39;love,you,hate,number&#39;, E&#39;,+&#39;) AS ytt; ytt -------- love you hate number (4 rows) t_girl=#
登入後複製
第三种,用自带的WITH 语法来实现。 
登入後複製
t_girl=# with recursive ytt(f1,f2) as (
values (0,&#39; &#39;::text) 
union all 
select f1+1,split_part(&#39;love,you,hate,number&#39;,&#39;,&#39;,f1+1) from ytt where f1 < 20 
) 
select f2 as result from ytt where f1 >=1 and f1 <= length(&#39;love,you,hate,number&#39;)-length(replace(&#39;love,you,hate,number&#39;,&#39;,&#39;,&#39;&#39;))+1;
 result 
--------
 love
 you
 hate
 number
(4 rows)

Time: 0.742 ms
登入後複製
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板