0

这是一个 SQL 视图,显示与 ID 为“2”的书在同一书架上的图书数量。有没有一种简单的方法可以将其转换为可以输入图书 ID 的过程,而不是默认 ID 为“2”?我还没有冒险进入程序,这个特定的程序会涉及很多编码吗?

    SELECT COUNT(*) FROM books
    WHERE shelf_id = (SELECT shelf_id FROM books WHERE book_id = 2)

子查询是因为 Book 表有书架 ID,但书架不包含书架 ID。

4

2 回答 2

0

您的代码可能如下所示:-

CREATE PROCEDURE spBooks(@BookID integer)
AS
SELECT COUNT(*) FROM books
    WHERE shelf_id = (SELECT shelf_id FROM books WHERE book_id = @BookID)
GO;

那应该创建您想要的存储过程。

于 2012-12-01T20:27:32.187 回答
0

如果是 Oracle,请尝试以下操作:

    PROCEDURE GET_BOOK_COUNT(
        i_book_id            IN  books.book_id%TYPE,
        o_count              OUT NUMBER)
      AS
      BEGIN
            SELECT COUNT(*) INTO o_count  FROM books
            WHERE shelf_id = 
                         (SELECT shelf_id FROM books WHERE book_id = i_book_id );
      END GET_BOOK_COUNT;

但最好将其设为 afunction而不是procedureas:

      FUNCTION GET_BOOK_COUNT(
        i_book_id            IN  books.book_id%TYPE)
            RETURN NUMBER
            IS
            l_count Number;
            SELECT COUNT(*) INTO l_count  FROM books
            WHERE shelf_id = 
                         (SELECT shelf_id FROM books WHERE book_id = i_book_id );
            RETURN l_count;
      END GET_BOOK_COUNT;
于 2012-12-01T20:29:36.750 回答