Question

I have two tables

Book:

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

Copies:

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

So the Copies table entries for all the copies of a book (Book.no_of_copies is 5 then there are 5 copies (rows) in the Copies table)

How can I write a procedure that can take the input parameter as book_id and by first querying the Book table, find the no_of_copies. If the no_of_copies is positive, then query the Copies table and display the copy_number,shelf_letter and call_number for each result.

Was it helpful?

Solution 2

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;

OTHER TIPS

...Or, erm, you could just write this very simple query:

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

You can wrap this in a procedure if you must, but I can't imagine why you would need to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top