I am trying to create a table test_table
that has a column year
which takes an array of 'years', like so:
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
.
If the year
column is not an array, then the above command works fine and the table is created. However, by making the date an array, and by having the CONSTRAINT
, I get the following error:
ERROR: function date_trunc(unknown, date[]) does not exist
How do apply the CONSTRAINT
to the array column 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))
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.