Search code examples
mysqlsqlmariadbsql-function

Undeclared variable compid in mariaddb function


i try to create function to get id of company by phone number(varchar)

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

and have error:

Undeclared variable: compid

Solution

  • The error message is trying to tell you. You need to declare the variable before you can assign to it:

    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;
    

    Here is a Demo on DB Fiddle.