日期:2014-05-18  浏览次数:20459 次

SQL语句 问题
select   *   from   emp   where   emp_name   like   '%% '   and   EMP_SEX   like   '%% '   and   DEPT_ID   like   '%% '   and   DUTY_ID   like   '%% '   and   OPSITION_ID   like   '%% '   and   EMP_SPEC   like   '%% '   and   EMP_IDENTITY_CARD   like   '%% '  


愿句为:   string   sql   =   "select   *   from   emp   where   emp_name   like   '% "   +   name   +   "% '   and   EMP_SEX   like   '% "   +   sex   +   "% '   and   DEPT_ID   like   '% "   +   dept   +   "% '   and   DUTY_ID   like   '% "   +   duty   +   "% '   and   OPSITION_ID   like   '% "   +   option   +   "% '   and   EMP_SPEC   like   '% "   +   sep   +   "% '     and   EMP_IDENTITY_CARD   like   '% "   +   cardid   +   "% ' ";
请问我这语句有何问题???????????


------解决方案--------------------
LZ说: 这么写主要是我有7个参数,但是结合起来的判断条件要是一个一个来就有2的7次幂个条件。

那么下面这样可以么?

select * from emp where (参数1= ' ' or emp_name like '%参数1% ') and (参数2= ' ' or EMP_SEX like '%参数2% ') and (参数3= ' ' or DEPT_ID like '%参数3% ') and (参数4= ' ' or DUTY_ID like '%参数4% ') and (参数5= ' ' or OPSITION_ID like '%参数5% ') and (参数6= ' ' or EMP_SPEC like '%参数6% ') and (参数7= ' ' or EMP_IDENTITY_CARD like '%参数7% ' )
------解决方案--------------------
不用那么多If判断,这样写就可以:

select *
from emp
where (emp_name like '% ' + @emp_name + '% ' or @emp_name is null)
and (EMP_SEX like '% ' + @EMP_SEX + '% ' or @EMP_SEX is null)
and (DEPT_ID like '% ' + @DEPT_ID + '% ' or @DEPT_ID is null)
and (DUTY_ID like '% ' + @DUTY_ID + '% ' or @DUTY_ID is null)
and (OPSITION_ID like '% ' + @OPSITION_ID + '% ' or @OPSITION_ID is null)
and (EMP_SPEC like '% ' + @EMP_SPEC + '% ' or @EMP_SPEC is null)
and (emp_name like '% ' + @EMP_IDENTITY_CARD + '% ' or @EMP_IDENTITY_CARD is null)

对于为空的,传入System.DBNull