Postgresql 函数中如何动态执行sql语句

实现功能,根据传入id删除多张表的数据:

CREATE or replace FUNCTION fn_delete ( p_deleteid INT )
 RETURNS VARCHAR LANGUAGE 'plpgsql' AS 
 $$ 
DECLARE
sql1 VARCHAR ( 100 );
sql2 VARCHAR ( 100 );
sql3 VARCHAR ( 100 );
sql4 VARCHAR ( 100 );
BEGIN
sql1 := 'delete from AA where id_delete=$1';
EXECUTE sql1 using p_deleteid;
sql2 := 'delete from BB where id_delete=$1';
EXECUTE sql2 using p_deleteid;
sql3 := 'delete from CC where id_delete=$1';
EXECUTE sql3 using p_deleteid;
sql4 := 'delete from DD where id_delete=$1';
EXECUTE sql4 using p_deleteid;
RETURN 'SUCCESS';

END;
$$

类似于Oracle 中 execute immediate 用法,postgresql中使用关键字 EXECUTE 来动态的执行一个sql语句,参数同样使用 [ using 参数 ]进行传入。
动态执行sql语句会带来一些效率问题,在执行大量语句的时候不推荐使用。

你可能感兴趣的:(PostgreSql)