虽然真的很鸡肋,并且性能不杂滴,但聊胜于无吧.
drop function if exists exe_dynamic_sql(bigint);
drop function if exists exe_dynamic_count(bigint);
--返回记录集
create or replace function exe_dynamic_sql(ival bigint)
returns table(objectid bigint,name varchar(128))
as $$
declare
begin
return query execute 'select objectid,name from dictionarys where parentid=$1 order by parentid,sort' using $1;
end;
$$ language plpgsql;
--赋值给变量
create or replace function exe_dynamic_count(ival bigint)
returns bigint
as $$
declare
v_count bigint;
begin
execute 'select count(*) from dictionarys where parentid=$1' using $1 into v_count;
return v_count;
end;
$$ language plpgsql;
--测试
select * from exe_dynamic_sql(26);
select exe_dynamic_count(26);
要点:
- returns table(objectid bigint,name varchar(128)),定义返回的字段和类型
- using $1执行时使用过程参数;
准备一个语句用于执行,这个就比较重要了,查询参数绑定,开发利器
有朋友抱怨同一sql时快时慢,这是因为值在表中的占比不同,占比小的值就可以使用索引,值占比超过5%里sql就很慢了.此时就可以用下面的sql调式sql,可以根据不同的值来观察执行计划.
--getDictionarys仅在当前会话下有效
prepare getDictionarys (bigint) as
select objectid,name from dictionarys where parentid=$1 order by parentid,sort;
explain (analyze,verbose,costs,buffers,timing)
execute getDictionarys(24);
explain (analyze,verbose,costs,buffers,timing)
execute getDictionarys(25);
explain (analyze,verbose,costs,buffers,timing)
execute getDictionarys(26);
--释放指定的预备语句
deallocate getDictionarys;
--释放所有预备语句
deallocate all;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。