我有一个变量进入存储过程。该变量可以有值也可以为空。
- 如果变量为空,我需要选择表中的所有行(一些具有 NULL 值,一些具有实际数据)。
- 如果变量不为空,我只需要选择变量与列匹配的行。
我创建了这个条件语句来帮助解释我想要实现的目标:
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
这就是我想出的(其中之一):
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))
唯一的问题是如果bookStatus.status_desc
为 NULL,那么它不会选择该行(当@status 为空时)
我很困惑,我也尝试查找 Coalesce,它似乎优先考虑了这些值,但是......我不知道该怎么做。
我应该在存储过程中创建一个巨大的 CASE 并有两个 select 语句吗?