2013-06-21 61 views
2

是否可以通過存儲過程傳遞準備好的SELECT語句並執行它?分別 - 是否可以在存儲MySQL過程的SELECT語句中動態創建WHERE條件?MySQL存儲過程 - 將SELECT作爲參數傳遞

我們希望啓用40列以上的變量搜索。這意味着,有40 * 40個組合,我們也可以硬編碼(並獲得一些解決方案),但在我看來,這是太蠻力的方法。數據集大約有數千條記錄。

+2

SQL注入?? – Kermit

+0

像這樣的自由格式搜索,您將不可避免地會有昂貴的搜索,它們沒有索引,如果您正在構建的這個工具被廣泛使用,可能會拼出更大的問題。保重。一個看似簡單的SELECT可能會導致數據庫關閉。 –

回答

2

這是完全可能的。這裏是你所說的使用插入和更新的例子,而不是選擇,但這是你所需要的基本形式。此過程的目的是動態插入或更新。這個查詢的參數是insert或update語句的變量子句。我希望這個例子有助於解釋你想做什麼是可能的:

DROP procedure if exists `test`.`upsert_event`; 
DELIMITER $$ 

CREATE PROCEDURE `test`.`upsert_event`(IN UPDATE_PARAM VARCHAR(10240), IN INSERT_PARAM VARCHAR(10240), IN REMOTE_ID_STRING VARCHAR(255)) 
BEGIN 

    DECLARE event_id_value INT(12) DEFAULT 0; 
    DECLARE id_for_update INT(12) DEFAULT 0; 

    # this temp table allows results to be returned and gets around a bug in our version of mysql 
    CREATE TEMPORARY TABLE IF NOT EXISTS result_set(
     event_id int(12) DEFAULT 0, 
     is_inserted tinyint(1) DEFAULT 0 
    ) engine = memory; 

    SELECT `events`.`id` INTO id_for_update FROM `events` WHERE `events`.`remote_id` = REMOTE_ID_STRING limit 1; 

    # declare the variables that will be needed 
    IF id_for_update != 0 THEN 

     # build the update clause that you need 
     SET @query_as_string = CONCAT('UPDATE `events` SET ', UPDATE_PARAM, ' WHERE `events`.`remote_id` = ', REMOTE_ID_STRING); 

     PREPARE statement_1 FROM @query_as_string; 
     EXECUTE statement_1; 
     DEALLOCATE PREPARE statement_1; 

     INSERT INTO `result_set` (event_id, is_inserted) VALUES (id_for_update, 0); 

    ELSE    
     #build the insert clause that you need 
     SET @query_as_string = CONCAT('INSERT INTO `events` ', INSERT_PARAM); 

     PREPARE statement_1 FROM @query_as_string; 
     EXECUTE statement_1; 
     DEALLOCATE PREPARE statement_1; 

     # set the id of the value update/inserted and return that as a reference 
     SELECT LAST_INSERT_ID() INTO event_id_value; 
     INSERT INTO `result_set` (event_id, is_inserted) VALUES (event_id_value, 1); 

    END IF; 

    SELECT * FROM `result_set` WHERE 1 LIMIT 1; 
    DROP TABLE result_set; 

END $$ 
DELIMITER ; 
+0

我看到你使用某物。作爲準備語句:http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html看起來非常有用。謝謝! – Daniel

相關問題