zoukankan      html  css  js  c++  java
  • PG 存储函数调用变量的3种方法。

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

  • 相关阅读:
    python
    python
    python
    python
    python
    python
    python
    python
    [ThinkPHP] 从一个表中获得栏目对应的ID,从另一个表获得属于这些栏目的文章
    [thinkPHP] buildSql可以查看tp CURD操作对应的SQL
  • 原文地址:https://www.cnblogs.com/luokunlun/p/9048684.html
Copyright © 2011-2022 走看看