mariaddb 函数中未声明的变量 compid

Undeclared variable compid in mariaddb function

我尝试创建函数以通过 phone number(varchar)

获取公司 ID
CREATE OR REPLACE FUNCTION getIdByPhone (cp CHAR(255))
RETURNS  INT
BEGIN 
SELECT id into compid 
FROM companies 
WHERE comp_phone1=cp;
RETURN compid;
END;

有错误:

Undeclared variable: compid

错误信息试图告诉你。您需要 declare 变量才能赋值给它:

delimiter //

create function getidbyphone (cp char(255))
returns int
deterministic
begin 
    declare compid int;
    select id into compid from companies where comp_phone1 = cp;
    return compid;
end
//

delimiter;

这里是Demo on DB Fiddle.