简体   繁体   中英

MySQL Stored Function syntax error while defining INNER JOIN tables

My Sql code is like this :

DELIMITER $$

CREATE FUNCTION `get_theme`(`section_type` VARCHAR(50))
RETURNS VARCHAR(50)
CONTAINS SQL
SQL SECURITY DEFINER

BEGIN

DECLARE name,dirname VARCHAR(50) ;
SELECT a.name INTO name , a.dirname INTO dirname FROM themes as a
INNER JOIN sections as b ON 
a.section_id = b.id 
WHERE b.name = 'administrators' AND a.`status` = 'Y';

RETURN name + '#' + dirname;
END $$

DELIMITER ;

when I execute this code in heidiSQL 9.2.0.4961 I get this error : Not defined variable : a

but when i execute this code :

 SELECT a.name as name , a.dirname as dirname FROM themes as a
 INNER JOIN sections as b ON 
 a.section_id = b.id 
 WHERE b.name = 'administrators' AND a.`status` = 'Y';

there is no problem and it works completely fine.

what's wrong with my code ? any idea ?

The syntax you are using is wrong. A correct syntax is:

SELECT list_of_expressions INTO list_of_variables FROM ...


Replace this fragment:

SELECT a.name INTO name , a.dirname INTO dirname FROM themes as a

with this one:

SELECT a.name, a.dirname INTO name , dirname FROM themes as a

One remark: don't assign to variables the same names as column in the table has, for example: DECLARE name,dirname , it causes a confusion and errors if you want to use them later in the query. Use a prefix for variables, for example: DECLARE v_name,v_dirname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM