'declare exists_check int' 附近使用的语法错误

wrong syntax to use near 'declare exists_check int'

我正在编写一个脚本来更新数据库模式,脚本如下:

delimiter //

begin 
    set @check_exists = 0;

    select count(*)
    into @check_exists
    from information_schema.columns
    where table_schema = 'my_app'
    and table_name = 'users'
    and column_name = 'points';
        
    if (@check_exists = 0) then
        alter table my_app.users
        add points int not null default 0
    end if;
end //

delimiter 

当我 运行 它时,我得到以下错误:

Reason:
 SQL Error [1064] [42000]: (conn=34) You have an error in your SQL syntax; 
 check the manual that corresponds to your MariaDB server version for the right syntax 
 to use near 'set @check_exists = 0;

我已经检查了下面两个帖子的答案,但是 none 解决了我的问题。

我认为您需要在 BEGIN 语句之前有一个 CREATE PROCEDURE。所以:

delimiter //

CREATE PROCEDURE UPDATE_SCHEMA()
begin 
    set @check_exists = 0;
    (...your other script here...)
end//

delimiter ;

call UPDATE_SCHEMA();

附加说明:check_exists 在您的 if 语句中需要 @

根据 BEGIN END 文档 here,语法为:

BEGIN [NOT ATOMIC] [statement_list] END [end_label]

这是我不知道的:

NOT ATOMIC is required when used outside of a stored procedure. Inside stored procedures or within an anonymous block, BEGIN alone starts a new anonymous block.

因为我没有在存储过程中使用 BEGIN END,所以我必须在 BEGIN 关键字之后添加 NOT ATOMIC

所以代码应该是这样的:

delimiter //

begin not atomic
    set @check_exists = 0;


-- rest of the code here...