4

我有一个变量进入存储过程。该变量可以有值也可以为空。

  • 如果变量为空,我需要选择表中的所有行(一些具有 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 语句吗?

4

4 回答 4

6
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) ...

更新
添加了两个条件,for@author@status

于 2012-06-12T15:06:53.937 回答
3

如果您考虑一下您的描述,它会分解为:

  • 当@status 为空时返回所有行
  • 否则返回匹配@status 的行。

你可以表达你的 sql 的最后一行来匹配这样的:

(@status is null OR bookStatus.status_desc LIKE @status)
于 2012-06-12T15:09:48.133 回答
0

我总是用这个:

WHERE 字段名 = ISNULL(@parameter, 字段名)

希望这有助于罗杰

于 2014-07-30T11:08:56.417 回答
0

where(field1 like isnull(@parameter,field1))

如果参数为 null 将检索 field1 中的所有数据,例如

select field from table1

这适用于sybase。

于 2015-09-11T21:45:01.107 回答