I was trying to create a calendar table. The query below. I get the error in the title. Can someone explain why?
create table if not exists test_calendar (test_date date primary key);
do $$
declare
i intEGER := 0 ;--, date datetime := '20090101';
Begin
while i <= 10 loop
begin
insert into test_calendar (test_date) values (dateadd(dd,i,'20090101'));
i := i + 1;
end;
end Loop;
$$ ;
SELECT * FROM test_calendar
The immediate cause of the error message is the missing
ENDat the end.A semicolon after the final
ENDis optional.But there is more:
There is no
dateadd()function in Postgres (like in SQL Server). You can simply addintegerto adatefor your purpose.The expensive nested block serves no purpose. Remove it.
Such a loop is simpler and cheaper with
FOR. See:Proper way
All of the above is just proof of concept. What I really would do:
db<>fiddle here
A set-based solution is generally better for this. Use
generate_series()in Postgres. Detailed explanation:A single multi-row
INSERTis much cheaper than many single-rowINSERTcommands.The generated
timestampvalues are cast todatein the assignment. In other contexts you may need to cast explicitly.Typically, you don't even need a persisted calendar table at all in Postgres. Just use
generate_series()directly. Might be even faster.