[英]Postgres - array date column with constraint
I am trying to create a table test_table
that has a column year
which takes an array of 'years', like so:我正在尝试创建一个表
test_table
,该表的year
列采用“年”数组,如下所示:
CREATE TABLE avg_yearly_currencies_used (
id serial PRIMARY KEY,
year date[],
CONSTRAINT first_jan_check CHECK ( date_trunc('year', year) = year )
);
The CONSTRAINT
checks to see if the date is in the format such as: 2010-01-01
, or 2012-01-01
. CONSTRAINT
检查日期是否采用以下格式: 2010-01-01
或2012-01-01
。
If the year
column is not an array, then the above command works fine and the table is created.如果
year
列不是数组,则上述命令可以正常工作并创建表。 However, by making the date an array, and by having the CONSTRAINT
, I get the following error:但是,通过将日期设为数组并使用
CONSTRAINT
,我得到以下错误:
ERROR: function date_trunc(unknown, date[]) does not exist
How do apply the CONSTRAINT
to the array column year
?如何将
CONSTRAINT
应用于数组列year
?
You can use following approach您可以使用以下方法
create function check_date (
date_ date[]) returns boolean as
$$
declare
result boolean;
begin
select bool_and (date_trunc('year', n) = n) into result
from unnest(date_) s(n);
return result;
end;
$$
language plpgsql immutable;
CREATE TABLE avg_yearly_currencies_used (
id serial PRIMARY KEY,
year date[],
CONSTRAINT first_jan_check CHECK (check_date(year))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.