where 子语句中,有下列要求:如果A字段为1,则y=1,如果A字段为2,则x=1,如果A字段为3,则y=1同时x=1注:A字段为select from 表中的某字段,y和x都是where子语句中的检索条件求写法

解决方案 »

  1.   

    不是很理解,前面字段中的内容,怎么可以控制你where后面的条件?declare @table table (A int,X int,Y int)
    insert into @table
    select 1,1,1 union all
    select 2,1,2 union all
    select 3,0,1select * from @table
    /*
    A           X           Y
    ----------- ----------- -----------
    1           1           1
    2           1           2
    3           0           1
    */
      

  2.   

    case a when 1 then y=1 when  2 then x=1 when 3 then y=1 and x=1 end
      

  3.   

    哦,写错了,A不是字段,是某变量。根据A的值来where不同的条件进行检索
      

  4.   

    是我没写清楚,补充一下:select * from tabel1 
    where w = 'xxx'
    and z = 5
    and ......即我发帖要追加的where条件,根据A值的不同追加不同的条件
      

  5.   


    declare @table table (A int,X int,Y int)
    insert into @table
    select 1,1,1 union all
    select 2,1,2 union all
    select 3,0,1declare @A int
    set @A=1if(@A=1)
    select * from @table where Y=1
    if(@A=2)
    select * from @table where X=1
    if(@A=3)
    select * from @table where X=1 AND Y=1
      

  6.   


    declare @sql varchar(8000)
    set @sql='select * from tabel1 where w = ''xxx'' and z = 5'
    +case @A when 1 then ' and Y=1' when 2 then 'and X=1'
    when 3 then 'and X=1 AND Y=1' END 
    exec(@sql)
      

  7.   

    and 前面我少写了个空格declare @sql varchar(8000)
    set @sql='select * from tabel1 where w = ''xxx'' and z = 5 '
    +case @A when 1 then ' and Y=1' when 2 then ' and X=1'
    when 3 then ' and X=1 AND Y=1' END 
    exec(@sql)
      

  8.   

    楼上的老大,请问不用@sql这个中间变量,直接写sql语句,怎么写啊?
      

  9.   

    要么直接写就类似5楼那种要么动态拼接,就是需要变量的,处理完语句后exec执行。
      

  10.   

    就你目前的这个需求,确实可以变通处理一下:declare @table table (A int,X int,Y int)
    insert into @table
    select 1,1,1 union all
    select 2,1,2 union all
    select 3,0,1declare @A int
    set @A=3 --改成1 或是2 运行可以看结果select * from @table 
    where 
    Y=isnull(case @A when 1 then 1 when 3 then 1 else null end,Y)
    and X=isnull(case @A when 2 then 1 when 3 then 1 else null end,X)
      

  11.   


    declare @sql nvarchar(4000)set @sql ='select * from TableName where case A when 1 then y = 1 when 2 then x=1 else  y=1 and x=1 end'exec @sql