0

我有两张桌子

书:

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)
  ) ;

所以一本书的所有副本的副本表条目(Book.no_of_copies 是 5,那么副本表中有 5 个副本(行))

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

4

2 回答 2

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

如果必须,您可以将其包装在一个过程中,但我无法想象您为什么需要这样做。

于 2013-10-01T09:42:14.773 回答
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;

或者

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;
于 2013-10-01T09:05:03.117 回答