【问题标题】:Dynamic conditions in SQL where clause by passing parametersSQL where 子句中的动态条件通过传递参数
【发布时间】:2017-09-07 20:10:47
【问题描述】:

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

但它给出了一个语法错误,谁能帮助我,谢谢。

【问题讨论】:

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


    【解决方案1】:

    您不能使用 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...*/
        )
    

    【讨论】:

      猜你喜欢
      • 2019-01-26
      • 2020-07-25
      • 1970-01-01
      • 2021-01-11
      • 2011-10-20
      • 2019-05-13
      • 1970-01-01
      • 2010-12-15
      • 2023-03-27
      相关资源
      最近更新 更多