PostgreSQL 9.5.4.
I have a function which returns array of days between two dates in string form. It's based on this code:
select (generate_series('2012-06-29', '2012-07-03', '1 day'::interval))::date
This code gives five dates in output, it's ok.
But if I do this in function:
DECLARE
dates date[];
BEGIN
select (generate_series('2012-06-29', '2012-07-03', '1 day'::interval))::date into dates;
return array_to_string(dates, ',');
END;
Then there is an error like this: "Invalid array literal '2012-06-29'. The value of the array must begin with "{" or specify the dimension. "
How can I fix this?
Generate a series of numbers in postgres by using the generate_series function. The function requires either 2 or 3 inputs. The first input, [start], is the starting point for generating your series. [ stop] is the value that the series will stop at. The series will stop once the values pass the [stop] value.
Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows. PostgreSQL offers unnest() function.
A Set Returning Function is a PostgreSQL Stored Procedure that can be used as a relation: from a single call it returns an entire result set, much like a subquery or a table. It used to be possible to use SRF in the SELECT clause, with dubious (but useful at times) semantics, and also in scalar contexts.
When you are considering portability (e.g. rewriting your system to work with other databses) then you must not use arrays. If you are sure you'll stick with Postgres, then you can safely use arrays where you find appropriate. They exist for a reason and are neither bad design nor non-compliant.
You can use the array constructor:
DECLARE
dates date[];
BEGIN
select array(select generate_series('2012-06-29', '2012-07-03', '1 day'::interval)::date)
into dates; --need semicolon here
return dates;
END;
If that code is actually a function, then you can simplify it to a SQL function
create function get_dates()
returns date[]
$$
select array(select generate_series(current_date - 6, current_date, interval '1' day)::date);
$$
language sql;
"Invalid array literal '2012-06-29'. The value of the array must begin with "{" or specify the dimension. "
SELECT
returns a row set
,
ARRAY()
function can convert row set
into an array
.
and the reverse function is UNNEST()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With