简体   繁体   中英

Mysql - Creating Stored Procedure

Using Ver 14.12 Distrib 5.0.45 (I know it's old),

file: storedprocedure.sql contains:

DELIMITER //
CREATE PROCEDURE loadDashboard 
(
    IN limitStr int(11)
)
BEGIN
    SELECT table123.ID
    FROM table123
    ORDER BY date_lastmodified LIMIT limitStr;
END //
DELIMITER ;

I've tried both executing this command-line with:

mysql -u root -p -h localhost DB < storedprocedure.sql

and from within

mysql -u root -p -h localhost DB

mysql> *copied the code in from storedprocedure.sql

The error I get is: ERROR 1064 (42000) 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 'limitStr ERROR 1064 (42000) 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 'limitStr

However, another question on StackOverflow uses this exact syntax and it worked for everyone else?

You were using a reserved word table . Try the following. Works fine as tested. If you need to use an if-y word like a Reserved Word, then surround it with back-ticks. This includes words for column names and tables that include a space or a hyphen.

schema:

drop table if exists mytable123;
create table mytable123
(
    id int auto_increment primary key,
    date_lastmodified datetime not null
);

insert mytable123(date_lastmodified) values ('2006-07-23'),('2006-07-27 13:10:09');

Stored proc:

drop procedure if exists loadDashboard;
DELIMITER //
CREATE PROCEDURE loadDashboard 
(
    IN limitStr int(11)
)
BEGIN
    DECLARE theLimit int;   -- to maintain compatibility (see comment from user wchiquito)

    set theLimit=limitStr;

    SELECT  ID
    FROM mytable123
    ORDER BY date_lastmodified 
    LIMIT theLimit; -- use the local variable for this
END //

DELIMITER ;

test:

call loadDashboard(1);
call loadDashboard(17);

MySQL Reserved Words ... the ones with an (R).

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