PLSQL过程查询两个表并循环遍历结果

时间:2013-10-01 08:54:41

标签: sql oracle stored-procedures plsql rdbms

我有两张桌子

图书:

CREATE TABLE Book
  (
book_id      INTEGER NOT NULL ,
shelf_letter CHAR (1) NOT NULL ,
call_number  INTEGER ,
no_of_copies INTEGER NOT NULL ,
CONSTRAINT isbn_unique UNIQUE (isbn),
) ;

份数:

CREATE TABLE Copies
  (
copy_id     INTEGER NOT NULL ,
book_id     INTEGER NOT NULL ,
copy_number INTEGER NOT NULL,
constraint copy_number_unique unique(book_id,copy_number)
  ) ;

因此,书籍的所有副本的Copies表条目(Book.no_of_copies为5,然后Copies表中有5个副本(行))

如何编写一个可以将输入参数作为book_id的过程,并首先查询Book表,找到no_of_copies。如果no_of_copies为正数,则查询Copies表并显示每个结果的copy_number,shelf_letter和call_number。

2 个答案:

答案 0 :(得分:2)

...或者,呃,你可以写这个非常的简单查询:

select copies.copy_number,
       book.shelf_letter,
       book.call_number
from   book
join   copies
on     copies.book_id    = book.book_id
where  book.book_id      = ???
and    book.no_of_copies > 0

如果必须,你可以将它包装在一个程序中,但我无法想象为什么你需要。

答案 1 :(得分:1)

CREATE PROCEDURE (P_BOOK_ID INTEGER)

    CURSOR C1(L_BOOK_ID INTEGER) IS
    SELECT * FROM COPIES WHERE BOOK_ID = L_BOOK_ID;
    L_NUM_COPIES NUMBER;

BEGIN

    SELECT NO_OF_COPIES INTO L_NUM_COPIES FROM BOOK WHERE BOOK_ID = P_BOOK_ID;

    IF L_NUM_COPIES>0
        THEN
            FOR CUR IN C1(P_BOOK_ID)
            LOOP
                DBMS_OUTPUT.PUT_LINE(CUR.COPY_NUMBER);
            END LOOP;

END;

OR

CREATE PROCEDURE (P_BOOK_ID INTEGER)

    CURSOR C1(L_BOOK_ID INTEGER) IS
    SELECT B.book_id,
           B.shelf_letter,
           B.call_number,
           B.no_of_copies,
           C.copy_id,
           C.copy_number
    FROM COPIES C,
         BOOK B
    WHERE C.BOOK_ID = L_BOOK_ID
    AND C.BOOK_ID=B.BOOK_ID;

    L_NUM_COPIES NUMBER;

BEGIN

    FOR CUR IN C1(P_BOOK_ID)
    LOOP
       DBMS_OUTPUT.PUT_LINE(CUR.book_id);   
       DBMS_OUTPUT.PUT_LINE(CUR.shelf_letter);
       DBMS_OUTPUT.PUT_LINE(CUR.call_number);   
       DBMS_OUTPUT.PUT_LINE(CUR.no_of_copies);
       DBMS_OUTPUT.PUT_LINE(CUR.copy_id);   
       DBMS_OUTPUT.PUT_LINE(CUR.copy_number);

    END LOOP;

END;