如何使用 SQL 程序添加新属性并同时更新值?

How to use SQL procedure to add new attribute and update the value at the same time?

我正在尝试创建一个过程,该过程 (1) 将名为 'Hours' 的新属性添加到名为 'Project' 的 table(如果它没有 'Hour'属性)和(2)将'Hour'的值初始化为0.0。下面是我试过的代码(使用 myPhpAdmin),但它给了我 SQL 语法错误。我做错了什么?

错误消息显示 "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 'UPDATE Project SET Hours = 0.0 where Project.Pnumber = p end if; end' "

delimiter &
create procedure init(in p int(11))
begin
    declare attNum int;
    SELECT COUNT(*) INTO attNum FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_schema = 'MyDB'
        AND table_name = 'Project';
    if attNum < 5 then ALTER TABLE Project ADD Hours float; 
    end if;

     SELECT * FROM Project 
     where Project.Pnumber = p 
     UPDATE Project SET Hours = 0.0
     where Project.Pnumber = p
end

(1)adds new attribute called 'Hours' to table called 'Project' (if it does not have the 'Hour' attribute) and (2)initialize the value of 'Hour' to 0.0.

为什么要为此使用存储过程?在任何情况下,您都可以使用 alter tabledefault 值来执行此操作:

alter table project add hours float default 0.0

Here 是一个 db<>fiddle.

我不建议将此类逻辑包装在存储过程中。据推测,它只被完成一次。如果您确实需要在存储过程中执行此操作,只需 运行 上述命令即可。如果该列已经存在,MySQL returns 一个错误 -- 您可以在存储过程中处理该错误。

存储过程创建查询中 Select 和更新查询末尾缺少分号。

更正查询:

delimiter &
create procedure init(in p int(11))
begin
    declare attNum int;
    SELECT COUNT(*) INTO attNum FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_schema = 'MyDB'
        AND table_name = 'Project';
    if attNum < 5 then ALTER TABLE Project ADD Hours float; 
    end if;

     SELECT * FROM Project 
     where Project.Pnumber = p;
     UPDATE Project SET Hours = 0.0
     where Project.Pnumber = p;
end