Scenario: Get List of Books by Author

We have a database named LibraryDB with a table Books.

Table Schema:

CREATE TABLE Books (
    BookId INT PRIMARY KEY,
    Title NVARCHAR(250),
    Author NVARCHAR(250),
    PublishedYear INT
);

Sample Data:

BookIdTitleAuthorPublishedYear
1SQL BasicsJohn Doe2020
2Advanced SQL TechniquesJane Smith2021
3Introduction to DatabasesJohn Doe2019
4Data Science EssentialsAlice Johnson2022

Stored Procedure to Get Books by Author

USE [LibraryDB]
GO
 
CREATE PROCEDURE GetBooksByAuthor
    @Author NVARCHAR(250),
    @MinYear INT = NULL -- Optional parameter for filtering by year
AS
BEGIN
    SET NOCOUNT ON;
 
    SELECT
        Title,
        Author,
        PublishedYear
    FROM
        Books
    WHERE
        Author = @Author
        AND (@MinYear IS NULL OR PublishedYear >= @MinYear)
    ORDER BY
        PublishedYear;
END
GO

Explanation of the Stored Procedure

  1. Input Parameters:

    • @Author: The author’s name to filter the books.
    • @MinYear: Optional parameter. If provided, filters books published after this year.
  2. Query Logic:

    • Select books where the Author matches the given input.
    • If @MinYear is provided, include only books published after or in the specified year.
    • Results are sorted by PublishedYear.

Executing the Stored Procedure

1. Call to Get Books by John Doe:

EXEC GetBooksByAuthor @Author = 'John Doe';

Result:

TitleAuthorPublishedYear
Introduction to DatabasesJohn Doe2019
SQL BasicsJohn Doe2020

2. Call with a Year Filter:

EXEC GetBooksByAuthor @Author = 'John Doe', @MinYear = 2020;

Result:

TitleAuthorPublishedYear
SQL BasicsJohn Doe2020