SQL Where 子句中的服务器条件
SQL Server Conditions in Where Clause
我正在使用 SQL 服务器 class。我在使用存储过程中的条件 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
我想将服务设置为必填项,将国家和地区设置为可选项。所以我希望能够像这样调用程序。所以,如果我不指定地区和国家,它应该只是 return all Navy。
这可能吗?
就性能而言,最好不要在 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)
试试这个:
Where (@country is null or @country = country)
And (@region is null or @region = region)
您要搜索的内容称为包罗万象的查询。
我正在使用 SQL 服务器 class。我在使用存储过程中的条件 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
我想将服务设置为必填项,将国家和地区设置为可选项。所以我希望能够像这样调用程序。所以,如果我不指定地区和国家,它应该只是 return all Navy。
这可能吗?
就性能而言,最好不要在 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)
试试这个:
Where (@country is null or @country = country)
And (@region is null or @region = region)
您要搜索的内容称为包罗万象的查询。