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)
I always use this:
WHERE fieldname = ISNULL(@parameter, fieldname)
Hope this helps Roger
where(field1 like isnull(@parameter,field1))
If the paramater is null will retrieve all data from field1 like
select field from table1
This works on sybase.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.