Oracle使用游标循环创建过程

时间:2013-04-08 03:13:29

标签: oracle loops stored-procedures cursor

我在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

1 个答案:

答案 0 :(得分:2)

这可能会更好一些。

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