![](/img/trans.png)
[英]MySQL Stored Procedures : Use a variable as the database name in a cursor declaration
[英]MySQL Stored Procedures : cursor declaration
抱歉,標題含糊,這是我的問題。 我已經存儲了DB2的存儲過程,並嘗試將其轉換為MySQL。 我想知道是否可以將游標聲明中的SELECT語句作為字符串變量編寫。 例如與DB2我有這樣的:
(...)
-- Declare cursors
DECLARE c_very_init CURSOR WITH RETURN FOR s_very_init;
DECLARE c_date CURSOR WITH RETURN FOR s_date;
DECLARE CONTINUE HANDLER FOR not_found
SET at_end = 1;
-- In case the_date is 0, retrieve the first date
IF the_date = 0 THEN
SET sql_end_date = '
SELECT DATE
FROM ACCOUNTS
WHERE REF = ''' || the_ref || '''
ORDER BY ID ASC FETCH FIRST 1 ROWS ONLY';
PREPARE s_date FROM sql_end_date;
OPEN c_date;
FETCH FROM c_date INTO data_ins;
SET the_last_date = data_ins;
CLOSE c_date;
ELSE
SET the_last_date = the_date;
END IF;
-- Get the 'very' initial value
SET sql_very_init = '
SELECT in, out
FROM MOVEMENTS
WHERE REF = ''' || the_ref || '''
AND DATE < ' || the_last_date;
PREPARE s_very_init FROM sql_very_init;
OPEN c_very_init;
FETCH FROM c_very_init INTO dare, avere;
-- Loop through the results
(...)
我聲明了一個c_very_init
游標,但是在SP中聲明游標時,我仍然不知道完整的select語句,因為我需要獲取(如有必要) the_last_date
值。 看來我做不到:
DECLARE c_very_init CURSOR WITH RETURN FOR s_very_init;
在MySQL中,語法直接在聲明中包含:
DECLARE c_very_init CURSOR FOR SELECT blaablaa...;
我錯了嗎?
謝謝。 fabien。
不,您不能以這種方式聲明游標。 但是,如果“ the_ref”是變量,則可以這樣進行操作-
...
DECLARE the_ref INT DEFAULT 10;
DECLARE cur1 CURSOR FOR SELECT column1 FROM table1 WHERE column1 = the_ref;
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.