如何在 SQL where 子句中执行条件语句
How to do a conditional statement in SQL where clause
我想要做的是当 @aValue
参数类似于 'abc%' 然后 运行
select
f.name, f.amount, f.date
from
fakeTable f
where f.name like @aValue
and f.date > '01/01/2000'
否则,如果 @aValue
参数与 'abc%' 不同,则 select 所有 f.name 等于 @aValue 的记录。
select
f.name, f.amount, f.date
from
fakeTable f
where f.name = @aValue
and f.date > '01/01/2000'
我正在尝试在我的 Where 中使用 CASE 语句来完成此操作。在我的 where 语句中,我收到一个错误
Incorrect syntax near LIKE
我的查询:
Declare @aValue varchar(5) = 'abcde';
-- @aValue = 'xyz';
select
f.name, f.amount, f.date
from
fakeTable f
where
f.name = case
when @aValue 'abc%'
then f.name like @aValue
else f.name = @aValue
end
and f.date > '01/01/2000'
我做错了什么导致语法错误?
而不是 CASE
表达式,使用 OR
和 AND
运算符,如下所示:
WHERE (
(@aValue LIKE 'abc%' AND f.name LIKE @aValue)
OR
(@aValue NOT LIKE 'abc%' AND f.name = @aValue)
)
AND f.date > '01/01/2000'
您可以使用布尔逻辑来代替尝试在 CASE 表达式中处理条件:
WHERE
(
f.name = @aValue
OR
(
@aValue LIKE 'abc%'
AND
f.name LIKE 'abc%'
)
)
我建议使用 union
并针对每种情况进行查询,这通常比尝试组合多个条件更好,后者会妨碍有效的索引使用。
类似于以下内容,@value 的第一个测试为真应该意味着只有一个或其他查询实际执行。
select <columns>
from table
where @value like 'abc%' and name like @value+'%'
union all
select <columns>
from table
where @value not like 'abc%' and name = @value
我想要做的是当 @aValue
参数类似于 'abc%' 然后 运行
select
f.name, f.amount, f.date
from
fakeTable f
where f.name like @aValue
and f.date > '01/01/2000'
否则,如果 @aValue
参数与 'abc%' 不同,则 select 所有 f.name 等于 @aValue 的记录。
select
f.name, f.amount, f.date
from
fakeTable f
where f.name = @aValue
and f.date > '01/01/2000'
我正在尝试在我的 Where 中使用 CASE 语句来完成此操作。在我的 where 语句中,我收到一个错误
Incorrect syntax near LIKE
我的查询:
Declare @aValue varchar(5) = 'abcde';
-- @aValue = 'xyz';
select
f.name, f.amount, f.date
from
fakeTable f
where
f.name = case
when @aValue 'abc%'
then f.name like @aValue
else f.name = @aValue
end
and f.date > '01/01/2000'
我做错了什么导致语法错误?
而不是 CASE
表达式,使用 OR
和 AND
运算符,如下所示:
WHERE (
(@aValue LIKE 'abc%' AND f.name LIKE @aValue)
OR
(@aValue NOT LIKE 'abc%' AND f.name = @aValue)
)
AND f.date > '01/01/2000'
您可以使用布尔逻辑来代替尝试在 CASE 表达式中处理条件:
WHERE
(
f.name = @aValue
OR
(
@aValue LIKE 'abc%'
AND
f.name LIKE 'abc%'
)
)
我建议使用 union
并针对每种情况进行查询,这通常比尝试组合多个条件更好,后者会妨碍有效的索引使用。
类似于以下内容,@value 的第一个测试为真应该意味着只有一个或其他查询实际执行。
select <columns>
from table
where @value like 'abc%' and name like @value+'%'
union all
select <columns>
from table
where @value not like 'abc%' and name = @value