SQL 中的动态条件 where 子句通过传递参数

Dynamic conditions in SQL where clause by passing parameters

我有一个SQL查询:

DECLARE @sy VARCHAR(10)
set @sy='>'

select EM.EmpId,EM.EmpName,ETR.Rating as Rating,
from [dbo].[EmploeeMaster_Data] as EM
join [dbo].[EmpTechRating_Data] as ETR on EM.EmpId=ETR.Emp_id
where EM.CompetencyId in (2,5) and ETR.Rating > 1

在where条件ETR.Rating > 1中,我想把'>'和参数@sy放在一起, @sy 值将类似于 '>'、'='、'<'、'>=' 等,基于我想放置条件的 @sy。我尝试将 case 和 IF 条件放在 where 子句

where EM.CompetencyId in (2,5) and Case @sy when '>' ETR.Rating > 1
when '<' ETR.Rating < 1
when '=' ETR.Rating = 1
END

但是它给出了语法错误,谁能帮我解决一下,谢谢。

您不能使用 case 语句来更改运算符。

你需要这样写:

AND (
    (@sy = '>' AND ETR.Rating > 1)
 OR (@sy = '<' AND ETR.Rating < 1)
 OR (@sy = '>=' AND ETR.Rating >= 1)
 OR (@sy = '<=' AND ETR.Rating <= 1)
    /* ETC...*/
    )