2012-02-11 69 views
0

我在执行此操作时遇到语法错误。是否可以使用有限变量而不使用concat函数?在concat中的语法错误和在mysql中的限制

CREATE PROCEDURE SP(_start INT,_end INT) 
BEGIN 
    DECLARE _qry VARCHAR(500) DEFAULT CONCAT('select * from tbl limit ',_start,_end); 
    PREPARE stmt FROM _qry; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 
END 

错误是

Error Code: 1064 
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 '_qry; 
EXECUTE stmt; 
+0

不是问题出在'_'? – 2012-02-11 10:25:59

+0

即使我删除那是越来越相同的错误 – DON 2012-02-11 10:28:46

+0

检查xdazz答案...您的问题解决了... – 2012-02-11 10:32:57

回答

1

我认为你必须改变DEFAULT DELIMITER第一和创造STORED PROCEDURE前添加PARAMETER DIRECTION

There are good reasons to use prepared statements: 
1.) Save on query parsing 
2.) Save on data conversion and copying 
3.) Avoid SQL Injection 
4.) Save memory on handling blobs 

There are also drawbacks and chewats of using prepared statements: 

1.) Query cache does not work 
2.) Extra server round trip required if statement used only once 
3.) Not all statements can be prepared. So you can’t use prepared API 
    exclusively you’ll need to fall back to normal API for some statements 
4.) Newer and sometimes buggy code. I had a lot of problems with PHP 
    prepared statements. It is getting better but still it is less mature 
    than standard API 
5.) You can’t use placeholders in place of all identifiers. For example you 
    can’t use them for table name. In certain version it even does not work for 
    LIMIT boundaries 
6.) Inconvenient list handling. Unlike in for example PEAR emulated prepard 
    statements there is no nice way to pass list of values to IN 
7.) Harder tracing. Logs were now fixed to include full statement text not 
    only “Execute” but in SHOW INNODB STATUS you would still see statements 
    without actual values – quite inonvenient for analyses. 

试试这个:

更新1

DELIMITER $$ 

CREATE PROCEDURE SP(IN _start INT,IN _end INT) 

BEGIN 

    SET @iQuery = CONCAT('select * from tbl limit ', _start, ',', _end); 

    PREPARE stmt FROM @iQuery; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 

END $$ 

DELIMITER ; 

MySQL Syntax for Prepared Statements

+0

我已经使用分隔符,必须有一些其他错误 – DON 2012-02-11 10:44:08

+0

我也添加了参数方向,但仍然得到相同的错误 – DON 2012-02-11 10:48:09

+0

@DON i更新我的答案基于MySQL文档 – 2012-02-11 10:54:31

2

你错过,偏移之前。

CREATE PROCEDURE SP(_start INT,_end INT) 
BEGIN 
    DECLARE _qry VARCHAR(500) DEFAULT CONCAT('select * from tbl limit ', _start, ',', _end); 
    PREPARE stmt FROM _qry; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 
END 
+0

,同样的错误在添加','后也是如此 – DON 2012-02-11 10:34:47

1
delimiter // 
drop procedure if exists SP // 
create procedure SP(_start int,_end int) 
begin 
    declare _qry varchar(500); 
    set @_qry = 'select * from tbl limit ?, ?'; 
    set @start = _start; 
    set @end = _end; 
    prepare stmt from @qry;  
    execute stmt using @start, @end; 
    deallocate prepare stmt; 
end; // 
delimiter ; 

call SP(1,2);