频道栏目
首页 > 资讯 > ORACLE > 正文

PostgreSQL-PL/pgSQL-cursor,loop

16-01-12        来源:[db:作者]  
收藏   我要投稿

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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结果集,再用分组查询可以统计到各个字符的数量。

1
select proc1,count(*) from proc1() group by proc1 order by count desc;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
proc1 | count
-------+-------
 医    |    65
 院    |    61
 小    |    41
 1     |    38
 州    |    36
 0     |    35
 5     |    32
...省略1000行左右
 他    |     1
 丹    |     1
 扑    |     1
 朵    |     1
 债    |     1
 }     |     1
(1145 行记录)

 


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

 这样使用

1
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)

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

 

相关TAG标签
上一篇:磁盘碎片整理用Ghost
下一篇:postgresql 导出数据字典文档
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站