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

时间:2017-09-07 20:10:47

标签: sql stored-procedures sql-server-2012 where-clause

我有一个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

在哪里条件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

但它给出了语法错误,任何人都可以帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

您无法使用案例陈述来更改运营商。

你需要这样写:

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...*/
    )