jw1*_*432 2 sql-server case-statement
我正在尝试使用依赖于变量的 case 语句来确定我的 WHERE 子句的一部分,但它不喜欢我在做什么。这是我的查询(为简单起见进行了修改)
DECLARE @SalesType VARCHAR(10)
SET @SalesType = 'Bulk'
SELECT CASE
WHEN fwsf.Customer_Cardlock_Customer = 'True'
THEN 'CFN'
ELSE 'Bulk'
END AS 'Prod Type'
FROM TABLE t
WHERE CASE
WHEN @SalesType = 'Bulk' then t.customer_type = 'False'
WHEN @SalesType = 'CFN' then t.customer_type = 'True'
End
Run Code Online (Sandbox Code Playgroud)
换句话说,我想在 WHERE 子句中声明,当 @SalesType 是给定值时,选择具有另一个值的行。
编辑:为了其他人,我意识到我有另一种情况,我可能需要选择“全部”选项。根据下面的 Shawn,他用我验证过的以下内容更正了我最初提出的解决方案:
AND t.customer_type =
CASE @SalesType
WHEN 'Bulk' then 'False'
WHEN 'CFN' then 'True'
WHEN 'All' then t.customer_type
END
END
Run Code Online (Sandbox Code Playgroud)
您可以WHERE更简单地编写子句:
where
(@SalesType = 'Bulk' and t.customer_type = 'False')
OR
(@SalesType = 'CFN' and t.customer_type = 'True')
OR
@SalesType = 'All'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |