我有一个查询语句(存储过程中)select aa,bb,cc,ddd
from tb1 a
inner join tb2 b on a.id=b.id and b.aa>0 or (b.code='99' and b.aa<0)
where ....现在有一个控制开关 declare @Flag int我想用这个参数 来 控制 查询条件and b.aa>0 or (b.code='99' and b.aa<0)case @Flag when 1 then 执行这个条件 when 0 不执行条件-----------------------------------千万不要告诉我根据参数再写一遍 SQL 语句
if @Flag=1
begin
   带条件
end else
begin
   不带条件
end这是最后的方法,因为我的SQL语句太多,这样复制几遍没法维护了

解决方案 »

  1.   

    這樣呢?
    select aa,bb,cc,ddd
    from tb1 a
    inner join tb2 b on a.id=b.id and b.aa>0 or (b.code='99' and b.aa<0)
    where (@Flag = 1 and (b.aa>0 or (b.code='99' and b.aa<0))) Or @Flag = 0
      

  2.   

    不是這樣控制的
    declare @sql varchar(8000)
    set @sql = 'select aa,bb,cc,ddd from tb1 a inner join tb2 b on a.id=b.id'
    if @flag = 1
    set @sql = @sql + 'and b.aa>0 or (b.code='99' and b.aa<0)'
    set @sql = @sql + 'where ....'exec(@sql)
      

  3.   

    看錯了Declare @Flag int
    Select @Flag = 1
    select aa,bb,cc,ddd
    from tb1 a
    inner join tb2 b on a.id=b.id and((@Flag = 1 and (b.aa>0 or (b.code='99' and b.aa<0))) Or @Flag = 0)
      

  4.   

    declare @sql varchar(8000)
    declare @Flag int
    set @Flag=1set @sql='select aa,bb,cc,ddd from tb1 a inner join tb2 b on a.id=b.id '+
    case when @Flag=1 then 'and b.aa>0 or (b.code=''99'' and b.aa<0) ' else '' end
    exec(@sql)
      

  5.   

    1=(case b.aa>0 and @Flag=1 then 1 else 0 end)
    and
    1=(case (b.code='99' and b.aa<0) and @Flag=0 then 1 else 0 end)
      

  6.   

    to yrwx001():
    你的方法可行,不过我的风格不会用 组合的SQL语句我试一下paoluo(一天到晚游泳的鱼)的方法,方法肯定没问题,主要是对效率影响有多大
      

  7.   

    效率肯定沒有直接中動態語句的好。不過yrwx001() 的有點小問題,單引號沒有處理。 :)
      

  8.   

    to libin_ftsafe(子陌红尘:TS for Banking Card) :你的语句稍微有点问题,这样做,有可能什么也查不到了