SQL 服务器 - where 子句上的 CASE
SQL Server - CASE on where clause
我正在处理一个 select 查询的存储过程。在 WHERE
子句下,仅当存在 PageTitle= 'STA'
时,我才将 return 结果过滤为 return
这是我的查询示例:
@InputCountryId INT,
@InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
r.PageTitle = 'STA'
END
结束条件 r.PageTitle
我希望仅在 InputCountry = 1
不适用时应用它;不包括过滤器。
我已经通过添加 CASE
来尝试这样做。每当我尝试介绍这种情况时,我都会遇到语法错误。这是可能的吗?我实施不正确吗?
这是包含 CASE
的存储过程示例。
@InputCountryId INT,
@InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
CASE WHEN @InputCountryId = 1 THEN
r.PageTitle = 'STA'
END
END
这样试试:
WHERE
r.IdCountry = @InputCountryId and
r.IdIndustry = @InputIndustryId and
(@InputCountryId <> 1 or r.PageTitle = 'STA')
您不需要 case 语句。您可以使用 OR
子句
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
(@InputCountryId != 1 OR r.PageTitle = 'STA')
这仅在 InputCountry 为 1 时使用 STA 过滤 PageTitle
我无法使用您的数据进行测试,但 WHERE 子句中的 CASE 有效。
DECLARE @Variable INT = 3
SELECT GETDATE()
WHERE 1 =
CASE
WHEN @Variable = 1 THEN 1
WHEN @Variable = 3 THEN 1
WHEN @Variable = 5 THEN 1
ELSE 0
END
我正在处理一个 select 查询的存储过程。在 WHERE
子句下,仅当存在 PageTitle= 'STA'
这是我的查询示例:
@InputCountryId INT,
@InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
r.PageTitle = 'STA'
END
结束条件 r.PageTitle
我希望仅在 InputCountry = 1
不适用时应用它;不包括过滤器。
我已经通过添加 CASE
来尝试这样做。每当我尝试介绍这种情况时,我都会遇到语法错误。这是可能的吗?我实施不正确吗?
这是包含 CASE
的存储过程示例。
@InputCountryId INT,
@InputIndustryId INT
AS
BEGIN
SELECT
r.IdCountry,
r.IdIndustry,
r.PageTitle,
r.IndustryName
From dbo.Reports r
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
CASE WHEN @InputCountryId = 1 THEN
r.PageTitle = 'STA'
END
END
这样试试:
WHERE
r.IdCountry = @InputCountryId and
r.IdIndustry = @InputIndustryId and
(@InputCountryId <> 1 or r.PageTitle = 'STA')
您不需要 case 语句。您可以使用 OR
子句
WHERE
r.IdCountry = @InputCountryId
r.IdIndustry = @InputIndustryId
(@InputCountryId != 1 OR r.PageTitle = 'STA')
这仅在 InputCountry 为 1 时使用 STA 过滤 PageTitle
我无法使用您的数据进行测试,但 WHERE 子句中的 CASE 有效。
DECLARE @Variable INT = 3
SELECT GETDATE()
WHERE 1 =
CASE
WHEN @Variable = 1 THEN 1
WHEN @Variable = 3 THEN 1
WHEN @Variable = 5 THEN 1
ELSE 0
END