【问题标题】:SQL Server Conditions in Where ClauseWhere 子句中的 SQL Server 条件
【发布时间】:2015-06-10 15:39:26
【问题描述】:

我正在学习 SQL Server 课程。我在使用存储过程中的条件 Where 子句时遇到问题。 3 个参数中有 2 个可能为 Null。

@Service nvarchar(50),
@Country nvarchar(50)  = NULL,
@Region nvarchar(50) = NULL

as 

SELECT
  CASE @Service
    WHEN 'Army' THEN Sum(Army)
    WHEN 'Navy' THEN Sum(Navy)
    When 'Marine_Corps' then Sum(Marine_Corps)
    When 'Air_Force' then Sum(Air_Force)
                ELSE NULL
  END

  as "ServiceTotal"

FROM
  All_Records

 WHERE 

if @Country is not null @Country and if @Region !=Null @Region = Region

如何重构 Where 子句?我来自 Access 背景。

GetTotals Navy

OR

GetTotals Navy,Albania,Europe

我想将服务设为强制性,国家和地区设为可选。所以我希望能够像这样调用程序。所以,如果我不指定地区和国家,它应该只返回所有海军。

这可能吗?

【问题讨论】:

    标签: sql sql-server tsql stored-procedures


    【解决方案1】:

    就性能而言,最好不要在WHERE 子句中使用函数。

    SELECT  CASE @Service
                WHEN 'Army' THEN Sum(Army)
                WHEN 'Navy' THEN Sum(Navy)
                When 'Marine_Corps' then Sum(Marine_Corps)
                When 'Air_Force' then Sum(Air_Force)
                ELSE NULL
            END AS "ServiceTotal"
    FROM All_Records
    WHERE Country = CASE WHEN @Country IS NOT NULL THEN @Country ELSE Country END
    AND Region = CASE WHEN @Region IS NOT NULL THEN @Region ELSE Region END
    

    使用ISNULL函数

    SELECT  CASE @Service
                WHEN 'Army' THEN Sum(Army)
                WHEN 'Navy' THEN Sum(Navy)
                When 'Marine_Corps' then Sum(Marine_Corps)
                When 'Air_Force' then Sum(Air_Force)
                ELSE NULL
            END AS "ServiceTotal"
    FROM All_Records
    WHERE Country = ISNULL(@Country ,Country)
    AND Region = ISNULL(@Region ,Country)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      Where (@country is null or @country = country)
      And (@region is null or @region = region)
      

      您正在搜索的内容称为包罗万象的查询。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-08
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多