2015-12-31 57 views
0

我對MySQL存儲過程並不是很熟悉,但我試圖第一次寫一個。在我的程序中,我有2個參數,其中一個或兩個都可以爲null。我需要創建一個遊標來循環,但我的遊標需要基於in參數。如果1爲空而另一個不爲空,那麼我的光標查詢就不同了。MySQL存儲過程基於參數的光標

例如:

CREATE PROCEDURE test (IN date timestamp, IN id int(11)) 
BEGIN 
    DECLARE cur CURSOR FOR 
    IF timestamp IS NOT NULL THEN 
      IF id IS NULL THEN 
       SELECT columns FROM Table WHERE modified_on <= timestamp 
      ELSE 
       SELECT columns FROM Table WHERE userid = id AND modified_on <= timestamp 
    ELSE 
      /* Logic here to pull query without the timestamp and where userid matches if the id passed in is not null */ 
    END IF 
END 

有人能告訴我如何實現一個簡單的例子?

+0

更改爲'where (id爲null或userid = id)'並使用相同的光標選擇查詢 – amdixon

+0

@amdixon謝謝我會給它一個鏡頭 – Phil

+0

@amdixon,如果你寫你的評論作爲答案我會接受作爲正確的答案。謝謝你的幫助! – Phil

回答

1

問題

  • 語法錯誤,declare cursor statement需要將正好與一個選擇查詢有關:

    DECLARE cursor_name CURSOR FOR select_statement

  • 還表是reserved keyword並需要轉義(或使用不同的名稱):

    SELECT columns FROM Table

修復,可以創建兩個光標一個用於每個場景或者在一個選擇查詢

設置

create table `Table` 
(
    id integer primary key auto_increment not null, 
    userid integer not null, 
    modified_on datetime not null 
); 

修復嵌入兩個查詢路徑

-- option one : combine queries into one 
drop procedure if exists test; 
delimiter $$ 
CREATE PROCEDURE test (IN date timestamp, IN id int(11)) 
BEGIN 
    DECLARE cur CURSOR FOR SELECT columns FROM `Table` WHERE (id is null or userid = id) and modified_on <= timestamp; 
    -- open and read from cursor.. 
END$$ 
delimiter ; 

-- option two define two cursors and use conditional logic below to decide which to read from 
drop procedure if exists test; 
delimiter $$ 
CREATE PROCEDURE test (IN date timestamp, IN id int(11)) 
BEGIN 
    DECLARE cur1 CURSOR FOR SELECT columns FROM `Table` WHERE modified_on <= timestamp; 
    DECLARE cur2 CURSOR FOR SELECT columns FROM `Table` WHERE userid = id AND modified_on <= timestamp; 
    -- evaluate if/else logic here to decide which cursor to open and use.. 
END$$ 
delimiter ; 

注意:不清楚你計劃爲每個遊標提取計劃什麼。取決於你的用例,它可能可以在沒有遊標的情況下完成。如果是這種情況,不使用一個光標,並保持該處理更接近天然SQL基於集合的處理


參考