SQL Server - How to create IF EXISTS...SELECT AND SELECT

Viewed 1427

I am attempting to create an IF/ELSE check on my code in order to ensure that the parameters @BookTitle and @GenreName are records within the the tables BookGenre and Genre before attempting to delete them. I attempted to write this line of code, but received an error,

An expression of type non-Boolean type specified where condition is expected.

IF EXISTS (SELECT Id FROM Library.Book WHERE Title = @BookTitle AND 
               SELECT Id FROM Library.Genre WHERE Name = @GenreName)
ELSE

I need some direction on how to create an IF EXISTS statement expression that includes two separate select statements as part of the IF check.

Here is the entire Store Procedure below (Without the IF statement):

PROCEDURE [Library].[DeleteDateFromBookGenre]
        -- Parameters to select which record delete
        @BookTitle nvarchar(200),
        @GenreName nvarchar(50)
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

        IF EXISTS (SELECT Id FROM Library.Book WHERE Title = @BookTitle) 
        IF EXISTS (SELECT Id FROM Library.Book WHERE Title = @BookTitle)

        -- Deletes the specified and selected data from the Genre and Book table.
        DELETE FROM Library.BookGenre 
        WHERE BookId IN (
        SELECT Id
        FROM Library.Book
        WHERE Title = @BookTitle
        ) AND
        GenreId IN (
        SELECT Id
        FROM Library.Genre
        WHERE Name = @GenreName
        )
    END
1 Answers

Your parentheses are off; you need two EXISTS conditions:

IF EXISTS (SELECT Id FROM Library.Book WHERE Title = @BookTitle
          ) AND 
   EXISTS (SELECT Id FROM Library.Genre WHERE Name = @GenreName
          )
BEGIN
    . . .
END
Related