I have a variable coming into a stored procedure. This variable can either have a value or be null.
I created this conditional statement to help explain what I would like to achieve:
if
@status is null, select all the rows (rows with NULL for table.status, and rows with actual data for table.status)
else
select the rows where @status equals table.status
This is what I came up with (well one of them):
WHERE
book.book_nme LIKE @search_input AND
book.book_desc LIKE @search_input AND
(book.author LIKE ISNULL(@author, book.author)) AND
(bookStatus.status_desc LIKE ISNULL(@status, bookStatus.status_desc))
The only problem is that if bookStatus.status_desc
is NULL, then it will not select that row (when @status is null)
I'm so confused, I tried looking up Coalesce too which seemed to prioritize the values, but ... I don't know what to do.
Should I just create a huge CASE in the stored procedure and have two select statements?
WHERE book.book_nme LIKE @search_input AND
book.book_desc LIKE @search_input AND
(@author IS NULL OR book.author LIKE @author) AND
(@status IS NULL OR bookStatus.status_desc LIKE @status) ...
Update
Added both conditions, for @author
and @status
If you think it about your description it breaks down as:
You can express the last line of your sql to match this like this:
(@status is null OR bookStatus.status_desc LIKE @status)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With