Mysql - 创建存储过程

Kol*_*yon 2 mysql command-line stored-procedures

使用Ver 14.12 Distrib 5.0.45(我知道它很旧),

文件:storedprocedure.sql包含:

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

我已经尝试使用以下命令执行此命令行:

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

并从内部

mysql -u root -p -h localhost DB

mysql> *copied the code in from storedprocedure.sql

我得到的错误是: 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

但是,StackOverflow 上的另一个问题使用了这种确切的语法,并且对其他人有用吗?

Dre*_*rew 6

您使用的是保留字table。请尝试以下操作。经测试工作正常。如果您需要使用像保留字这样的 if-y 字,请用反引号将其括起来。这包括包含空格或连字符的列名和表的单词。

架构:

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');
Run Code Online (Sandbox Code Playgroud)

存储过程:

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 ;
Run Code Online (Sandbox Code Playgroud)

测试:

call loadDashboard(1);
call loadDashboard(17);
Run Code Online (Sandbox Code Playgroud)

MySQL保留字...带有 (R) 的保留字