postgresql - 如何在 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);
我假设我做错了什么,但谷歌搜索文档并没有给我答案。这个问题的正确程序是什么?
解决方案
变量只能保存基础数据类型的完整值。您也不能只存储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);
...
推荐阅读
- php - 具有基本身份验证的用户的 Laravel 速率限制 api
- jmeter - Jmeter 结果不一致,取决于正在运行的机器
- flutter - 如何在颤动中改变 SfSlider 的高度和宽度?
- python - folium 地图上 CircleMarkers 的数量有限制吗?
- docker - 从 Dockerfile 运行时在 Docker 中找不到命令
- jaxb - cxf-codegen-plugin:3.4.2:wsdl2java 不生成正确的 Javadoc
- php - Laravel HTTP 客户端发布响应保存文件
- libreoffice - CALC BASIC 宏 - 求解线性方程组矩阵
- sql - 在 id 上为第一行可用的 SQL BigQuery 加入两个表
- css - 如何自定义 CSS Dark 叠加层的渐变