简体   繁体   中英

MySQL Stored Function Syntax Error

I've spent hours and I can't understand why this is highlighted red and I don't know what my error is.

CREATE FUNCTION Student_Section_Count(StudentID INT)

Returns INT

Begin 

DECLARE section_Registred INT;

SET section_Registred= (Select COUNT(DISTINCT Section.ID) as 'Students Registration Count'

FROM Section
Inner Join
Registration on registration.StudentID=Section.ID

Where registration.StudentID=StudentID);

Return Section_Registred;

END$$

Delimiter;

It highlights END and Delimiter, as well as INT from Return INT

Well, I guess I figured it out on my own.

DELIMITER $$

CREATE FUNCTION Student_Section_Count(StudentID INT)

Returns INT

Begin 

DECLARE section_Registred INT;

SET section_Registred= (Select COUNT(DISTINCT Section.ID) as 'Students Registration Count'

FROM Section

Inner Join

Registration on registration.StudentID=Section.ID

Where registration.StudentID=StudentID);

Return Section_Registred;

END$$

By default semi-colon ; is the delimiter in mysql. So when using a mysql client, the function definition that is passed to server is only up to the first semi-colon ie DECLARE section_Registred INT; . Rest of the definition of function is not passed to server. This produces an error. To incorporate semi-colon in function definition you need to change your delimiter from semi-colon to some thing else. So before defining the function write the below sql to change the delimiter:

DELIMITER $$ .

After the above sql write sql for your function. Append the new delimiter $$ to END at the end of definition of your function. Now the whole definition of function is passed to server up to the new delimiter. This will fix your error. Change the delimiter back to default after your function definition ends as below:

DELIMITER ; .

Also remember to choose a delimiter that is not present anywhere inside your function definition.

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