Where子句与存储过程中的条件

时间:2014-09-28 23:46:48

标签: sql sql-server tsql stored-procedures

我的存储过程(SQL Server)中有以下查询:

SELECT 
    ea.attendanceid,
    ea.employeeid,

    FROM employee_attendance ea

    WHERE 
    ea.masterentity = @masterentity
    AND ea.employeeid = @employeeid

    -- here I need to know what value @type is and then create my conditionals
    AND (ISNULL(@type,'') = '' OR 
        .......

我的参数@type有不同的字符串值:

  • IL =内部午餐
  • EL =外部午餐
  • L =所有午餐
  • N =仅正常
  • R = Especial

根据值,我必须过滤的列:

If `@type='IL'` then I have to filter: `AND ea.lunchtype = 'C'`
If `@type='EL'` then I have to filter: `AND ea.lunchtype = 'CI'`
If `@type='L'` then I have to filter: `AND ea.islunch = 1`
If `@type='N'` then I have to filter: `AND ea.islunch = 0`
If `@type='R'` then I have to filter: `AND (ea.ismanual = 1 AND ea.lunchtype = 'K')`

关于如何实现这一目标的任何线索?

2 个答案:

答案 0 :(得分:1)

您需要以类似的方式转换为SQL

AND ( 
ISNULL(@type, ' ') = ' '
OR ( @type='IL' AND ea.lunchtype = 'C' )
OR ( @type='EL' AND ea.lunchtype = 'CI' )
OR (@type='L' AND ea.islunch = 1   )
OR (@type='N' AND ea.islunch = 0    )
OR (@type='R'  AND (ea.ismanual = 1 AND ea.lunchtype = 'K')
)
)

答案 1 :(得分:0)

使用CASE声明。

CASE可用于允许有效表达式的任何语句子句。例如,您可以在SELECT,UPDATE,DELETE和SET等语句中使用CASE,也可以在select_list,IN, WHERE ,ORDER BY和HAVING等子句中使用CASE。

MSDN CASE (Transact-SQL)

请参阅本页上有关如何使用的示例。