这听起来可能是一个非常愚蠢的问题,但如何为PostgreSQL 9.3查询声明一个变量?

CREATE or replace FUNCTION public.test()
  returns int4
AS
$BODY$
DECLARE    
    cod_process bigint :=30001;
    cod_instance bigint ;
    utc_log timestamp without time zone := localtimestamp;
    cod_log_type varchar(100) :='information ';
    txt_log_text varchar(100):= 'start process';
    txt_log varchar(100):= txt_log_text||'_'||cod_process;
    set cod_instance= select max(cod_instance) as cod_instance from public.instance where public.instance.cod_process=cod_process;    
BEGIN  
    INSERT INTO public.log (cod_process, cod_instance, utc_log,cod_log_type,txt_log)
    VALUES (cod_process, cod_instance, utc_log,cod_log_type,txt_log );
    RETURN 11;
END;
$BODY$ LANGUAGE 'plpgsql';
ERROR: type "cod_instance" does not exist
SQL state: 42704
Character: 383

推荐答案

您需要在实际代码块中使用into子句运行select,而不是在declare块中:

begin
   select max(cod_instance) 
      into cod_instance
   from public.instance 
   where public.instance.cod_process=cod_process;

   ....
end;

为变量(或参数)指定与表中列相同的名称通常不是一个好主意.在某些情况下,这可能会混淆解析器.为了避免任何潜在的问题,请try 为变量使用不同的名称,例如,在它们前面加前缀(例如,l_cod_process而不是cod_processl_cod_instance而不是cod_instance)

有关变量赋值的更多详细信息,请参见手册:http://www.postgresql.org/docs/current/static/plpgsql-statements.html

Postgresql相关问答推荐

在postgres中查找多个表中不同列的计数和总和

读取扩展坞合成中的UDP:IO/超时

尽管违反了部分索引约束,Postgres 插入仍在发生

当参数大小超过 393166 个字符时,PSQL 准备语句查询挂起

postgres hierarchy - 用祖先的值填充缺失值

在 jOOQ 中 Select 相同的命名列

当我写 SELECT ~1;在 Postgresql 上它给了我 -2 结果.这是什么原因?它一直持续〜4和-5等

Postgres 根据自己的估计 Select 一个更费时的查询计划

计算 PostgreSQL 中给定 GPS 坐标的日出和日落时间

推送到 Heroku 时出现带有 Postgres 的 Rails 迁移错误

postgreSQL 中对 utf-8 的 LC_COLLATE 和 LC_CTYPE 支持

带有初始数据的 docker postgres 不会在提交中持久化

带有 postgres 的 DOCKER 容器,警告:could not open statistics file "pg_stat_tmp/global.stat": Operation not permitted

将 PostgreSQL 配置为仅适用于 LOCALHOST 或指定的 ip + 端口

从 PostgreSQL 中的数字获取月份名称

如何 Select 列值为空的行?

psql:致命:connection requires a valid client certificate

判断materialized视图的上次刷新时间

根据 Helm 图表设置值

在 OS X 上使用 Postgres.app 时如何将 psql 放在路径上?