PostgreSQL-PL/pgSQL-cursor,loop

将spam_keyword表word字段的字符全部拆分,只是利用过程语言完成循环的操作而已。

create or replace function proc1() returns setof text as $$
declare
str text;
strlength int;
strreturn text;
i int;
curs1 refcursor; --声明游标
begin
open curs1 for select replace(word,' ','') from spam_keyword; --在loop前打开游标并绑定好范围,query定义范围的时候就把空格都替换掉
<<loop1>> --标签
loop
    fetch curs1 into str;
    if not found then exit;
    end if;
    i:=0; --每一次游标完成赋值后就把i初始化为0
    <<loop2>>
    loop
        i:=i+1;
        strreturn:=substring(str,i,1);
        strlength:=char_length(str);
        return next strreturn;
        exit when i>=strlength;
    end loop loop2;
end loop loop1;
close curs1;
end;
$$ language plpgsql

 返回的是setof结果集,再用分组查询可以统计到各个字符的数量。

select proc1,count(*) from proc1() group by proc1 order by count desc;
 proc1 | count 
-------+-------
 医    |    65
 院    |    61
 小    |    41
 1     |    38
 州    |    36
 0     |    35
 5     |    32
...省略1000行左右
 他    |     1
 丹    |     1
 扑    |     1
 朵    |     1
 债    |     1
 }     |     1
(1145 行记录)

 


写成通用的函数,通过指定参数来分割

create or replace function split_to_table(str text) returns setof text as $$
declare
strlength int;
strreturn text;
i int;
begin
i:=0;
loop
    i:=i+1;
    str:=replace(str,' ','');
    strlength:=char_length(str);
    strreturn:=substring(str,i,1);
    return next strreturn;
    exit when i>=strlength;
end loop;
end;
$$ language plpgsql

 这样使用

select split_to_table(word) from spam_keyword;

 

后来突然想起来去看看是不是本来就有分割字符的函数在。。一查果然有。。。席巴。。。

函数:regexp_split_to_array(string text, pattern text [, flags text ])
说明:Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information. 利用正则表达式将字符串分割成数组
例子:regexp_split_to_array('hello world', E'\\s+') = {hello,world}

函数:regexp_split_to_table(string text, pattern text [, flags text])
说明:Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information. 利用正则表达式将字符串分割成表格
例子:regexp_split_to_table('hello world', E'\\s+') =
hello
world
(2 rows)

select regexp_split_to_table(word,E'') from spam_keyword;

 

posted @ 2015-12-01 10:10  Right-dress  阅读(2387)  评论(0编辑  收藏  举报