码迷,mamicode.com
首页 > 其他好文 > 详细

PG 存储函数调用变量的3种方法。

时间:2018-05-16 23:54:26      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:bsp   调用   tle   body   exe   fun   应用   结合   ola   

一、假设有表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来实现。

PG 存储函数调用变量的3种方法。

标签:bsp   调用   tle   body   exe   fun   应用   结合   ola   

原文地址:https://www.cnblogs.com/luokunlun/p/9048684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!