<span style="color: rgb(73,73,73); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(226,226,226);">postgre存储过程使用PL/pgSQL语言,</span>
PL/pgSQL是一种块结构的语言,基本方式如下:
CREATE OR REPLACE FUNCTION 函数名(参数1,[整型 int4,整型数组 _int4,…])
RETURNS 返回值类型 AS
$BODY$
DECLARE
变量声明
BEGIN
函数体
END;
$BODY$
LANGUAGE ‘plpgsql’ VOLATILE;
功能描述:从查询的结果中利用表名查询所需内容。
create or replace function fff(userid int)
returns setof record as --返回类型,结果集
$$
declare
sql varchar; --定义变量
asql varchar;
re record;
fav record;
begin
sql = 'select DISTINCT type as tablename from bmap_favorite where type<>'''||'0'|| '''and userid='''|| userid ||'''';
-----sql
for re in execute sql loop --循环执行后的结果集
asql = 'select f.gid,f.favtime,a.name,a.city,a.district,a.province,a.address,st_x(a.geom) as x,st_y(a.geom) as y
from '|| re.tablename ||' a,bmap_favorite f where a.gid = cast(f.gid as INTEGER) and f.userid=2 and f.type='''|| re.tablename ||'''';
for fav in execute asql loop
return next fav;
end loop;
end loop;
return;
end
$$
language plpgsql;
<h2 class="entry_title" style="margin: 0px; padding: 0px; border: 0px; line-height: 22px; background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;"><pre name="code" class="sql"><span style="font-family:FangSong_GB2312;font-size:14px;font-weight: normal;"><span style="background-color: rgb(255,255,255);">1.</span><span style="background-color: rgb(255,255);">执行存储过程中,出现“set-valued function called in context that cannot accept a set”的错误</span></span>
,在数据库里执行函数,可以写“select funciton();”也可以写“select * from function()”
2.出现PostgreSQL: ERROR: 42601: a column definition list is required for functions returning “record”的错误
select * from fff(2) as f(gid varchar,favtime varchar,name VARCHAR,city varchar,district varchar,provice varchar,address varchar,x float,y float) --执行存储过程
需要在添加查询内容对应的类型。