【问题标题】:Trying to create Postgres function尝试创建 Postgres 函数
【发布时间】:2020-01-10 08:20:42
【问题描述】:

在 Postgress GUI 的创建屏幕中,我在 while 语句中遇到语法错误。语言是 plpgsql,返回类型是 void。 TIA

在此处输入代码

begin  
declare counter integer := 1;  
declare CurrentDate Date := '1/1/2018';  
    while CurrentDate < '1/1/2019'  
    loop  
        insert into dimCalendar select CurrentDate, EXTRACT(DOW FROM  
current_date), EXTRACT(DOY FROM  current_date);  
        CurrentDate := CurrentDate + 1;  
    end loop  
end

【问题讨论】:

  • 向我们展示完整代码。但是declare 需要 begin 之前,你只需要一个declare'1/1/2018' 是字符串文字而不是日期。但你不需要一个函数来开始。
  • 嘿,谢谢,正如你所说,我可以通过移动声明来编译/保存它。 '1/1/2018' 应该作为一个日期,因为变量被声明为 Date。就像 select cast('12/31/2018' as date) + 1 产生 2019-01-01。是的,我想我不需要为此使用函数,但尝试内联编写它更麻烦。

标签: postgresql


【解决方案1】:

下一次,请尝试包含所有代码

始终使用 ISO 日期格式,除非您有理由不这样做

declare 位于begin 之前

“结束循环”后缺少分号

请在PostgreSQL中使用snake_case

create or replace function foo() returns void as $$
declare
    counter integer := 1;
    curr_date date := '2018-01-01';
begin

    while curr_date < '2019-01-01' loop

        raise notice 'curr_date: %', curr_date;

        curr_date := curr_date + 1;

    end loop;

end
$$ language plpgsql;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2018-08-03
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多