SQL:如果参数为空,则选择所有行,否则仅选择匹配的行

标签 sql sql-server-2008-r2 isnull

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

  • 如果变量为空,我需要选择表中的所有行(一些为 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 为 null 时)

    我很困惑,我也尝试查找 Coalesce,它似乎优先考虑值,但是......我不知道该怎么做。

    我应该在存储过程中创建一个巨大的 CASE 并有两个选择语句吗?

    最佳答案

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

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

    关于SQL:如果参数为空,则选择所有行,否则仅选择匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999322/

    相关文章:

    java - hibernate native 查询错误 : Column not found

    mysql - 在单个查询中以不同条件两次从同一列获取值

    c# - 错误 :RESTORE cannot process database 'Test_DB' because it is in use by this session

    sql-server - 如何检查 SQL Server 中的阻塞查询

    sql - 必须为存储过程声明标量变量错误

    mysql - sql 将行从一个表移动到另一个表

    java - 如何从字符串为唯一索引数据库列创建哈希?

    sql-server - 在 SQL 中使用 ISNULL 的可控制查询

    mysql - LEFT JOIN 和 IS NULL 工作但不是 SUM 函数