【问题标题】:SQL Server 2016 - Get NULL values from a table using a Stored ProcedureSQL Server 2016 - 使用存储过程从表中获取 NULL 值
【发布时间】:2021-06-09 14:57:42
【问题描述】:

我正在尝试使用名为 GetCompanies 的存储过程和名为 @ShowCompaniesWithoutClients 的参数来显示所有公司(来自名为 Company 的表),其中 Client 列为 NULL 或为空( '')。

目前我找到的解决方案是创建一个 IF/ELSE 声明,其中验证 IF @ShowCompaniesWithoutClients=1 我命令

SELECT *  
FROM [Company] 
WHERE [Client] IS NULL OR [Client] = ''

否则,选择所有列(无限制)。

谁能帮我重构这个解决方案,用我不需要SELECT 声明两次的解决方案替换它?

免责声明:这只是一个实际应用的示例,我有大约 20 列和更多参数。

【问题讨论】:

    标签: sql sql-server database stored-procedures refactoring-databases


    【解决方案1】:

    所以@ShowCompaniesWithoutClients as bit 可以有 3 个可能的值,0、1 和 null。 0 和 1 是明确的,但是当您通过 @ShowCompaniesWithoutClients = null 表示所有内容都应该返回时,您可以这样做:

    SELECT * 
    FROM [Company] 
    WHERE  (ISNULL([Client],'') = ''  and @ShowCompaniesWithoutClients  = 1)
        OR (ISNULL([Client],'') <> '' and @ShowCompaniesWithoutClients  = 0)
        OR (@ShowCompaniesWithoutClients IS NULL)
    

    【讨论】:

    • 非常感谢,这正是我所需要的!
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多