2013-04-08 23 views
0

我在Oracle中創建一個過程來搜索參數中指定的一些關鍵字並打印出該行。這是我的代碼如下。它的工作原理,但我不知道爲什麼它不斷打印最後一行兩次。請幫助Oracle使用遊標循環創建程序

CREATE TABLE Testimonial(TestimonialID integer PRIMARY KEY, 
       Content char(100)); 

INSERT INTO Testimonial VALUES (100,'Great website'); 
INSERT INTO Testimonial VALUES (101,'I like it'); 
INSERT INTO Testimonial VALUES (102,'I bought two items from here and I really like them'); 
INSERT INTO Testimonial VALUES (103,'My girlfriends likes my presents I bought here'); 
INSERT INTO Testimonial VALUES (104,'Nice products'); 
INSERT INTO Testimonial VALUES (105,'Friendly customer service'); 

COMMIT; 


Create or replace procedure Search_Testimonials (search_string IN char) 
IS 
     Testimonial_record Testimonial%ROWTYPE; 

cursor cur_Testimonial is 
    select * 
    from Testimonial 
    WHERE content LIKE '%' || search_string || '%'; 
BEGIN 
    open cur_Testimonial; 
    Loop 
     Fetch cur_Testimonial into Testimonial_record; 
     DBMS_OUTPUT.PUT_LINE('Content: ' || Testimonial_record.content); 
     EXIT WHEN cur_Testimonial%NOTFOUND; 
    END LOOP; 
    close cur_Testimonial; 
    COMMIT; 
END; 
/

set serveroutput on 

exec Search_Testimonials('bought') 

輸出

Content: I bought two items from here and I really like them 
Content: My girlfriends likes my presents I bought here 
Content: My girlfriends likes my presents I bought here 
+0

必須是相當女人的男人和多個女朋友! – OldProgrammer 2013-04-08 03:17:08

+0

我猜它需要在NOTFOUND爲真之前移過最後一條記錄。 – 2013-04-08 03:27:38

+0

不,原因很簡單,在調用DBMS_OUTPUT之後正在檢查NOTFOUND。 – 2013-04-08 05:20:01

回答

2

這可能工作好一點。

Loop 
    Fetch cur_Testimonial into Testimonial_record; 
    EXIT WHEN cur_Testimonial%NOTFOUND; 
    DBMS_OUTPUT.PUT_LINE('Content: ' || Testimonial_record.content); 
END LOOP; 
+0

是的,它的工作原理。非常感謝。不知道它爲什麼會變得不同。 – Harry 2013-04-08 03:35:45

+1

因爲我猜它需要在它知道NOTFOUND之前移過最後一條記錄,並且在它確實存在時,它仍然必須包含.content – 2013-04-08 03:46:35

+0

中的最後一條記錄。是否現在要標記爲正確? – 2013-04-08 22:37:43