“错误:输入结束时的语法错误”运行时命令
我试图创建一个日历表。以下查询。我在标题中得到错误。有人可以解释为什么吗?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误消息的直接原因是最后一个缺少
结束
。最终
结束
之后的分号是可选的。但是还有更多:
postgres中没有
dateadd()
函数(例如在sql server中/a>)。您只需将整数
添加到Date
出于您的目的。昂贵的嵌套的块 无用。删除它。
对于,这样的循环更简单,更便宜。请参阅:
上面的所有方法
都是概念的证明。我真正会做的是:
db&lt; em>
基于设定的解决方案通常对此更好。在Postgres中使用
generate_series()
。详细说明:单个多行
插入
比许多单行 insert 命令便宜得多。分配中生成的
timestamp
值将date
施加到。在其他情况下,您可能需要明确施放。
通常,您甚至根本不需要持久的日历表。只需直接使用
generate_series()
。可能甚至更快。The immediate cause of the error message is the missing
END
at the end.A semicolon after the final
END
is optional.But there is more:
There is no
dateadd()
function in Postgres (like in SQL Server). You can simply addinteger
to adate
for 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
INSERT
is much cheaper than many single-rowINSERT
commands.The generated
timestamp
values are cast todate
in 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.