5

我有这个 sql 文件:

USE mydb;

DROP PROCEDURE IF EXISTS execSql;
DELIMITER //
CREATE PROCEDURE execSql (
                     IN sqlq VARCHAR(5000)
                      ) COMMENT 'Executes the statement'
BEGIN
  PREPARE stmt FROM sqlq;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //
DELIMITER ;          

当我尝试运行它时

# 猫文件.sql | mysql -p

我明白了

ERROR 1064 (42000) at line 6: 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 'sqlq;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  END' at line 5

我究竟做错了什么?

4

2 回答 2

25

您只能准备和执行作为字符串文字或包含语句文本的用户定义变量的 SQL。

试试这个:

USE mydb;

DROP PROCEDURE IF EXISTS execSql;
DELIMITER //

CREATE PROCEDURE execSql (IN sqlq VARCHAR(5000)) COMMENT 'Executes the statement'
BEGIN
  SET @sqlv = sqlq;
  PREPARE stmt FROM @sqlv;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //

DELIMITER ;      
于 2011-11-06T01:53:57.533 回答
2

您可以使用CONCATENATE,PREPAREEXECUTE语句如下:

CREATE DEFINER=`products`@`localhost` PROCEDURE `generateMeritList`(
   IN `mastercategory_id` INT(11), 
   IN `masterschools_id` INT(11)
) NO SQL
BEGIN

  DECLARE total INT DEFAULT 0;
  DECLARE conditions varchar(255) DEFAULT ''; 
  DECLARE finalQuery varchar(60000) DEFAULT '';

  IF mastercategory_id > 0 THEN
    SET conditions =  CONCAT(' AND app.masterschools_id = ', mastercategory_id);
  END IF;

  SET @finalQuery = CONCAT(
    "SELECT *
    FROM applications app
    INNER JOIN masterschools school ON school.id = app.masterschools_id
    WHERE app.status = 'active' ", conditions, " LIMIT ", total); 

   PREPARE stmt FROM @finalQuery;
   EXECUTE stmt;
   DEALLOCATE PREPARE stmt;

END
于 2016-05-07T07:33:17.020 回答