date隐式转换为整数

问题描述 投票:0回答:2

我正在学习PL / pgSQL。我想在一栏中打印接下来的15天日期。所以我创建了以下功能:

CREATE or replace FUNCTION p15d() 
  RETURNS table(date_ date ) AS $$ 
  declare 
  i date := current_date; 
  ii date := current_date + integer '15'; 
 BEGIN 
  loop 
      return query execute'select ' || (i + interval '1 day')::date; 
      i = i + 1; 
      exit when i = ii; 
  end loop; 
 END; 
 $$ 
 LANGUAGE plpgsql; 

但是当我运行此函数时,我收到此错误:

ERROR:  structure of query does not match function result type
DETAIL:  Returned type integer does not match expected type date in column 1.
CONTEXT:  PL/pgSQL function p15d() line 8 at RETURN QUERY
postgresql date time plpgsql
2个回答
3
投票

您不需要动态SQL来为表达式添加间隔。

CREATE or replace FUNCTION p15d() 
  RETURNS table(date_ date ) AS $$ 
  declare 
  i date := current_date; 
  ii date := current_date + integer '15'; 
 BEGIN 
  loop 
      return query  select ( i + interval '1 day' )::date; 
      i = i + 1; 
      exit when i = ii; 
  end loop; 
 END; 
 $$ 
 LANGUAGE plpgsql; 

但是,没有必要这样的功能,Postgres已经有了generate_series功能,可以提供你想要的功能。

CREATE or replace FUNCTION p15d() 
  RETURNS table(date_ date ) AS 
 $$ 
   select generate_series(current_date+1,current_date + 15,interval '1 day' )::date; 
 $$ 
 LANGUAGE SQL; 

Demo


1
投票

您的错误消息的原因是您执行的查询是(今天):

select 2019-03-02

现在2019减3减2是2014,这是一个整数。

© www.soinside.com 2019 - 2024. All rights reserved.