Why did this error happened when created EVENT with compound statement?

三世轮回 提交于 2019-12-02 22:03:33

问题


From this SO question. I got confused with DELIMITER. And I also tried something like following:

CREATE EVENT test
ON SCHEDULE EVERY 2 MINUTE
DO
BEGIN
SELECT 1;
SELECT 2;
END

This got me error like mentioned question:

Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5.

And if I ran the sql following:

DELIMITER $$
CREATE EVENT test
ON SCHEDULE EVERY 2 MINUTE
DO
BEGIN
SELECT 1;
SELECT 2;
END $$
DELIMITER;

This worked and created a new EVENT sucessfully.

The only difference between these two sql is the last one used DELIMITER, so my question is why DELIMITER works here. Can anyone explain to me?

Any help is appreciated and thanks in advance.


回答1:


It is real trivial, but hard to explain.

The delimiter out of the box is a ; ... That is how mysql knows the statement has ended. But things like stored procedures, events, functions have many statements in them. It needs an outer wrapper for the whole thing to know where it begins and where it ends.

So, you reset the delimiter at the beginning to something bizarre, like $$, put that $$ right after the END, then reset back to factory so to speak to ;

You are going to come up with Error 1064 all the time without it for the creation of stored procedures, events, functions, triggers. And you will burn a lot of time chasing your tail looking for the syntax error that is not there. Well, quite often. When in reality it lacks the DELIMITER wrapper.




回答2:


Your answer lies in the docs here 21.1 Defining Stored Programs

If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.



来源:https://stackoverflow.com/questions/37825627/why-did-this-error-happened-when-created-event-with-compound-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!