Mysql将动态内容传递给存储过程中的sql查询

时间:2014-12-24 04:18:47

标签: mysql sql stored-procedures

DROP PROCEDURE IF EXISTS test1();

DELIMITER //

 CREATE PROCEDURE test1( IN contextFilter TEXT )
   BEGIN
   SET @query =  'SELECT profileId AS \'profile\' from sa.topology_network_element' where contextFilter;
   PREPARE stmt_query FROM @query;
      SELECT @query;
        EXECUTE stmt_query;
        DEALLOCATE PREPARE stmt_query;
   END //

 DELIMITER ;

我试图传递我将在UI中选择的对象ID作为此查询的输入而不是“contextfilter”,而我正在尝试获取存储过程,我得到一些异常说“sql语法中的错误“,我无法弄清楚可能是什么错误

1 个答案:

答案 0 :(得分:0)

请注意注意代码。采取一切可能的安全措施。

DELIMITER //

DROP PROCEDURE IF EXISTS `test1`//

CREATE PROCEDURE `test1`(IN `contextFilter` TEXT)
BEGIN
  SET @`query` := CONCAT('SELECT `profileId` AS `profile`
                   FROM `sa`.`topology_network_element` WHERE ', `contextFilter`, ';');
  PREPARE `stmt_query` FROM @`query`;
  EXECUTE `stmt_query`;
  DEALLOCATE PREPARE `stmt_query`;
END//

DELIMITER ;

SQL Fiddle demo