Trying to use a CASE
statement in the WHERE
clause and it's giving me errors. What did I miss?
SELECT DISTINCT
Commodity,
Commodity_ID,
[Description],
Train,
Truck
FROM dbo.List_Commodity
WHERE
CASE WHEN @Truck = 1 THEN
Truck = @Truck
WHEN @Train = 1 THEN
Train = @Train
END
Instead of CASE
statement use AND/OR
logic to do this
SELECT DISTINCT commodity,
commodity_id,
[description],
train,
truck
FROM dbo.list_commodity
WHERE ( @Truck = 1
AND truck = @Truck )
OR ( @Train = 1
AND train = @Train )
In case you want to retrieve all the records when both @Truck
and @Train
are not equal to 1
then add the below condition to above query
OR ( @Train <> 1
AND @Train <> 1)
如果您期望THEN truck = @Truck
将返回true
或false
那么您将错过MS SQL没有布尔数据类型和布尔表达式的事实。
If you still want to use the CASE
statement, following query can be helpful:
DECLARE @Truck INT = 1 -- 1 is an example
DECLARE @Train INT = 1 -- 1 is an example
SELECT DISTINCT
Commodity,
Commodity_ID,
[Description],
Train,
Truck
FROM dbo.List_Commodity
WHERE 1 =
(
CASE
WHEN @Truck = 1 AND Truck = @Truck THEN 1
WHEN @Train = 1 AND Train = @Train THEN 1
END
)
PS: Please note that the CASE
statement only returns a value which should be compared it here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.