首页 > 数据库    PostgreSQL日期:2021-01-27 / 来自互联网 / 浏览

一、假设有表student,字段分别有id,remark,name等字段。

二、写一个存储函数,根据传过去的变量ID更新remark的内容。

调用该存储函数格式如下:

select update_student(1);

三、存储函数示例如下:

CREATE OR REPLACE FUNCTION public.update_student(id integer)
 RETURNS text AS
$BODY$
declare sql_str_run text; 
BEGIN
/*
--method 1
 select 'update student set remark ='''|| now() ||''' where student.id = '|| $1 into sql_str_run ;
 execute sql_str_run;
 --method 2
 execute 'update student set remark =now() where student.id=$1' using $1;
*/
 --method 3 
 update student set remark =now() where student.id=$1;
 
 return 'update is ok' ;
end
$BODY$
 LANGUAGE plpgsql VOLATILE

以上三种方法都可以实现同样的效果,实际应用中,可以结合场景来使用。比较简单的情况下直接用method 3。

比如,表名、字段名本身是变量,那么method 3 就无法实现,需要根据method 1或method 2来实现。

method 1或method 2 有什么区别呢?

如果需要拼的变量可以直接获取的,则用method2即可。如果变量本身也是需要需要通过函数或语句的计算来获得,一般建议用method 1,先拼成一个字符串,再调用execute来实现。

补充:postgresql存储函数/存储过程用sql语句来给变量赋值

--定义变量

a numeric;

方式一:

select sqla into a from table1 where b = '1' ; --这是sql语句赋值

方式二:

sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; --这是执行存储函数赋值

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章