mysat中的concat和limit的语法错误

时间:2012-02-11 10:22:49

标签: mysql limit concat

我在运行这个时遇到语法错误。是否可以在不使用concat函数的情况下使用带限制的变量?

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;

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我认为您必须首先更改DEFAULT DELIMITER并在创建PARAMETER DIRECTION之前添加STORED PROCEDURE

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

答案 2 :(得分: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);