我想做的是当@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%”,则选择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'
关于sql - 如何在 SQL where 子句中执行条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69195729/