好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

postgresql 存储函数调用变量的3种方法小结

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

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

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

?

1

select update_student(1);

三、存储函数示例如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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语句来给变量赋值

--定义变量

?

1

a numeric ;

方式一:

?

1

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

方式二:

?

1

2

sql1:= 'select a from table1 where b = ' '1' ' ' ;

execute sql1 into a; --这是执行存储函数赋值

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

原文链接:https://www.cnblogs.com/luokunlun/p/9048684.html

查看更多关于postgresql 存储函数调用变量的3种方法小结的详细内容...

  阅读:91次