2014-03-27 34 views
0

循環在功能上,我想寫這經過的記錄(僅整數IDS)列表中的SQL函數:SQL IN-基於MySQL中

  • 我不想手動枚舉所有的ID,即我想讓它們首先由SQL查詢返回,所以SET @recordlist =(SELECT ..),
  • 我想要一個循環爲每個執行另一個函數記錄列表的元素,即我希望能夠從FOR語句中的記錄列表中訪問每個單個元素

它應該看起來像:

SET @recordlist = (SELECT ..) 

For every element e in the recordlist 

Execute function f(e) 

回答

0

我用下面的代碼使它工作。只需複製&粘貼,更改查詢和函數的名稱。

DELIMITER $$ 
    DROP PROCEDURE IF EXISTS `my`$$ 
    CREATE PROCEDURE `my`() 
    BEGIN 
    DECLARE done INT DEFAULT FALSE; 
    DECLARE i INTEGER; 
    DECLARE curs1 CURSOR FOR SELECT DISTINCT `myval` FROM my_table; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
    OPEN curs1; 
    read_loop: LOOP 
    FETCH curs1 INTO i; 
    IF done THEN 
    LEAVE read_loop; 
    END IF; 
    SELECT myfunc(i); 
    END LOOP; 
    CLOSE curs1; 
    END$$ 
    DELIMITER ; 
0

使用常規使用循環光標實現這一目標!

delimiter// 
    create procedure get_balance() 
    begin 
    DECLARE var1; 
    DECLARE flag INT DEFAULT 0; 
    ....... 
     declare tcursor for select col1,col2.... from table; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag = 1; 
    open tcursor; 
    myloop:LOOP 
    fetch tcursor into col1,col2...; 
    if flag = 1 then 
    -- function here 
    call funtion; 
    leave myloop; 
    end if 
    end loop myloop; 
    close tcursor; 
    end// 
    delimiter; 
+0

Up_One for me! kkk Thx –