首页 > 解决方案 > 如何在 postgresql 中声明一个变量 INTERVAL?

问题描述

我想编写一个从 TIMESTAMP_START 到 TIMESTAMP_END 与变量 INTERVAL 交互的代码。我的硬编码工作代码如下所示:

LOOP 
    ...DO SMTH...

    TIMESTAMP_START := (TIMESTAMP_START + INTERVAL '30' MINUTE);
    EXIT WHEN TIMESTAMP_START > TIMESTAMP_END;
END LOOP; 

当我尝试替换间隔类型时,出现语法错误:

DECLARE INCREMENT_TYPE  INTERVAL := minute;
...
TIMESTAMP_START := (TIMESTAMP_START + INTERVAL '30' INCREMENT_TYPE);

当我尝试改变步骤时也会发生同样的情况:

DECLARE STEP    text    := '30'; 
...
TIMESTAMP_START := (TIMESTAMP_START + INTERVAL STEP MINUTE);

我假设我做错了什么,但谷歌搜索文档并没有给我答案。这个问题的正确程序是什么?

标签: postgresqldatetimetimestampplpgsqlintervals

解决方案


变量只能保存基础数据类型的完整值。您也不能只存储2018在时间戳变量中。

根据你想如何使用它,以及它应该有多灵活,我看到以下可能性:

declare 
   increment_value  interval := interval '30' minute;

begin
...
   timestamp_start := (timestamp_start + increment_value);
...

如果您只想定义一次增量值,这将很有帮助。


If you want to use different interval lengths throughout the function, you could define an interval of a standard length and then multiply that:

declare 
   one_minute_interval interval := interval '1' minute;
   one_hour_interval interval := interval '1' hour;

begin
...
   timestamp_start := (timestamp_start + 30 * one_minute_interval);
...
   timestamp_start := (timestamp_start + 5 * one_hour_interval);

Or a solution that is closer to what you are trying to do:

declare 
   increment_type  text := 'minute';

begin
...
   timestamp_start := (timestamp_start + ('30 '||increment_type)::interval);
...

推荐阅读