PostgreSQL如何连续区间值'2天'

d-m*_*man 12 postgresql datetime intervals

在PostgreSQL中我想current_timestampinterval以下内容连接:

select current_timestamp + interval 2||' days'
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我收到一个错误:

[Err] ERROR:  syntax error at or near "2"
LINE 1: select current_timestamp + interval 2||' days'
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,它可以正常工作:

select current_timestamp + interval '2 days'
Run Code Online (Sandbox Code Playgroud)

为什么一个工作,而另一个工作?

参考以下页面 http://www.postgresql.org/docs/8.0/static/functions-datetime.html

Mik*_*ll' 27

部分问题是间隔的标准SQL表达式引用了数字,而不是关键字.所以你必须要小心.

select current_date, current_date + interval '2' day;
--
2012-02-21   2012-02-23 00:00:00
Run Code Online (Sandbox Code Playgroud)

在PostgreSQL中,引用"2天"和"2天"也有效.所以你可能会认为'2'|| '天'是等价的,但事实并非如此.

select current_date, current_date + interval '2' || ' days';
--
2012-02-21   2012-02-21 00:00:02 days
Run Code Online (Sandbox Code Playgroud)

正如AH所说,解决方案是将结果字符串转换为间隔.

您也可以使用变量代替2.这将生成2012年的日历.

-- 0 to 365 is 366 days; 2012 is a leap year.
select ('2012-01-01'::date + (n || ' days')::interval)::date calendar_date
from generate_series(0, 365) n;
Run Code Online (Sandbox Code Playgroud)

我使用最终的强制转换,因为date + interval返回一个时间戳.


A.H*_*.H. 23

请尝试以下语法:

select current_timestamp + ( 2 || ' days')::interval;
Run Code Online (Sandbox Code Playgroud)

甚至这个:

select current_timestamp + 2 * interval '1 day';
Run Code Online (Sandbox Code Playgroud)


小智 6

我用这个

SELECT now() + (Var1 || ' ' || Var2)::interval
Run Code Online (Sandbox Code Playgroud)

无联系函数