PostgreSQL 執行動態sql
阿新 • • 發佈:2018-11-10
雖然真的很雞肋,並且效能不雜滴,但聊勝於無吧.
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;