日期:2014-05-18 浏览次数:20749 次
declare @sql nvarchar(max)
declare @a varchar(10),@b varchar(10),@c varchar(10);
select @a='2',@b='',@c='';
select @sql='select * from TableA as A inner join TableB as B  
on A.Id = B.Id AND 
((('''+isnull(@a,'''')+'''<>'''' and B.Type=1) or 1=1) 
and (('''+isnull(@b,'''')+'''<>'''' and B.Type=2) or 1=1)
and (('''+isnull(@c,'''')+'''<>'''' and B.Type=3) or 1=1))'
exec(@sql)
------解决方案--------------------
参考
select * from TABLEA a join TABLEB b on a.id=b.id where ( len(a.A)=0 or a.A is null or a.A=@A ) and ( len(a.B)=0 or a.B is null or a.B=@B ) and ( len(a.C)=0 or a.C is null or a.C=@C )
------解决方案--------------------
  select * from TableA as A inner join TableB as B  
on A.Id = B.Id 
where 
B.Type=(case 
    when @A is null or @A='' then B.type else @A end)
and 
B.Type=(case 
    when @B is null or @B='' then B.type else @B end)
AND
B.Type=(case 
    when @C is null or @C='' then B.type else @C end)
------解决方案--------------------
这问题楼主是不是想复杂了。
我们来看下,具体执行是按条件不同所以执行的语句不同,不同点在于其后列筛选的条件,那么楼主最终在数据库执行的就是一条SQL语句,至于取哪个条件,难道程序里不能在拼接SQL字符串的时候处理么?
switch(type){
case when 0: sql = sql + '';
case when 1: sql = sql + '';
break;
}
差不多是这种写法吧!或者 if {} else if {} ... else {} 等。