MySQL,stored-function,使用STRING变量作为QUERY

时间:2010-08-18 21:19:29

标签: stored-procedures mysql stored-functions

我想知道在mysql存储函数或存储过程中是否有可能将mysql查询组成一个字符串变量,以后可以执行?我有一个引用表的存储函数get_district_part ((district_id INT,county_id INT,city_id INT,zip_id INT)) RETURNS INT

CREATE TABLE IF NOT EXISTS `modx`.covereage_district_part(
    id      INT     NOT NULL    AUTO_INCREMENT  PRIMARY KEY,
    districtID  INT     NOT NULL,
    countyID    INT,
    cityID      INT,
    zipID       INT,
    FOREIGN KEY (districtID) REFERENCES `modx`.coverage_district (id),
    FOREIGN KEY (countyID) REFERENCES `modx`.coverage_county (id),
    FOREIGN KEY (cityID) REFERENCES `modx`.coverage_city (id),
    FOREIGN KEY (zipID) REFERENCES `modx`.coverage_zip (id)
);

get_distrct_part用于返回行district_id行的ID以及county_idcity_idzip_id的某些组合。问题是我想返回与id的确切组合匹配的行的id,而不是包含任何这些想法的行的id。为此,我想要分割我的查询语句,以便它是专门为所提供的ID构建的。如果可以,我试图不必匹配空值。

我意识到这可以通过PHP轻松完成,但我希望这样做作为mysql存储过程,如果我可以没有其他原因,那么所有其他功能都是存储过程。

1 个答案:

答案 0 :(得分:7)

是的,您可以PREPAREEXECUTE将字符串作为存储过程中的动态SQL。

delimiter //
CREATE PROCEDURE get_district_part (district_id INT, county_id INT, city_id INT, zip_id INT)
BEGIN
  SET @query = 'SELECT id FROM covereage_district_part WHERE 1=1';

  IF (district_id IS NOT NULL) THEN
    SET @query = CONCAT(@query, ' AND districtID=', district_id);
  END IF;

  IF (county_id IS NOT NULL) THEN
    SET @query = CONCAT(@query, ' AND countyID=', county_id);
  END IF;

  IF (city_id IS NOT NULL) THEN
    SET @query = CONCAT(@query, ' AND cityID=', city_id);
  END IF;

  IF (zip_id IS NOT NULL) THEN
    SET @query = CONCAT(@query, ' AND zipID=', zip_id);
  END IF;

  PREPARE stmt1 FROM @query;

  EXECUTE stmt1;
END //
delimiter ;

call get_district_part(1,1,1,1);
call get_district_part(1,1,null,null);

注意:但是,您无法在存储的函数中执行动态SQL。您的问题提到使用RETURNS子句声明您的例程,该子句将是一个存储函数。