postgresql 中 类似 oracle EXECUTE IMMEDIATE 的写法

pl/pgsql中,执行动态SQL的格式如下(摘录自说明文档):

1
EXECUTE command-string [ INTO [STRICT] target ] [ using expression [, ... ] ];

其中,

command-string就是要执行的动态sql语句(一定要记住:这里是sql语句,不是pl/pgSQL语句,像raise notice就不能使用);

INTO子句是把sql查询到的值赋给INTO指定的变量;

using子句是前面的command-string中替代变量($1, $2, ...)的赋值;

示例:

1
2
3
4
5
6
7
8
9
do $$
declare
v_c 1  integer;
v_c 2  integer;
begin
execute  'select count(*) as c1, count(*) as c2 from (select 1 as idx union select 11 as idx union select 21 as idx) s where idx > $1' 
into v_c 1 , v_c 2
using  10 ;

搜索

raise notice  '%, %' , v_c 1 , v_c 2 ;

猜你喜欢

转载自my.oschina.net/u/1264788/blog/483433