CREATE PROC CheckOutBook
@userID int,
@bookID int,
@startDate DateTime,
@stopDate DateTime,
@reqNumber int
AS
BEGIN
/* Setup variables */
DECLARE @cursorBookID int
DECLARE @count int
DECLARE c CURSOR
/* Counter used to control checkout */
SET @COUNT = 0
FOR
/* The cursor select statement */
SELECT book_id FROM dbo.books WHERE book_id = @bookID
OPEN c
/* Get row from cursor, store key value in given variable / FETCH c INTO @cursorBookID /* Loop through cursor data with global variable / WHILE ((@@FETCH_STATUS = 0) AND (@count < @reqNumber))
BEGIN /* Determine if book is checked out */
IF NOT EXISTS (
SELECT * FROM dbo.checked_out WHERE
((book_id = @cursorBookID) AND
(start_date BETWEEN @startDate AND @stopDate) AND
(stop_date BETWEEN @startDate AND @stopDate)))
BEGIN
/* Check out book if available / INSERT INTO
dbo.checked_out
(book_id, user_id, start_date, stop_date)
VALUES
(@cursorBookID, @bookID, @userID, @startDate, @stopDate)
SET @count = @count + 1
END /* Exit loop if requested number is met *.
If (@count > @reqNumber) goto exit_loop
FETCH c INTO @cursorBookID
exit_loop:
END
CLOSE c
DEALLOCATE c
END |