数据库中有一个字段存放写面的值:
x<=3|1,3<x<=5|2,5<x|4
字符串的含义表示,如果一个数<=3则给他赋值为1,如果一个数在3,5之间则给他赋值2,比5大则赋值3
我现在已经知道x的值,我如何把我的x带进上面的字符串球的|后面的值。
我现在使用charindex和replace函数可以获得 | 前面和后面的表达式,然后把整个操作符给一个字符串变量@sql,如果我直接使用execute(@sql)的话,一旦遇到3<x<=5的话就会报错。头大

解决方案 »

  1.   

    写成这样的
    X>3 and X<=5
      

  2.   

    现在数据库他们已经写成3<x<5这种形式了,我只能在他们写的这种形式上想办法。
      

  3.   

    declare @s varchar(60),@sql varchar(200)
    set @s='x<=3|1,3<x<=5|2,5<x|4'
    set @sql=''
    set @sql='select case when '+replace(PARSENAME(replace(@s,',','.'),3),'|',' then ')
    +' when '+replace(PARSENAME(replace(@s,',','.'),1),'|',' then ')+' else 2 end'
    exec(@sql)
      

  4.   

    print(@sql)
    select case when x<=3 then 1 when 5<x then 4 else 2 end
      

  5.   

    蝈蝈,都怪我偷懒了,实际上不是三种表达式,是多种。x<=3|1,3<x<=5|2,5<x<=7|4,7<x<=10|5,10<x|6
      

  6.   

    create table tb(c varchar(50))
    insert into tb values('x<=3|1,3<x<=5|2,5<x|4')
    go
    create proc my_proc @x as int , @rtn int OUTPUT
    as
    begin
    select @rtn = (case when @x <= d11 then d12
                when @x > d21 and @x <= d22 then d23
                when @x > d31 then d32
           end) from
    (
    select 
      cast(substring(c1 , charindex('=',c1) + 1 , charindex('|',c1) - charindex('=',c1) - 1) as int) d11,
      cast(substring(c1 , charindex('|',c1) + 1 , len(c1)) as int) d12,
      cast(substring(c2 , 1 , charindex('<',c1) - 1) as int) d21 ,
      cast(substring(c2 , charindex('=',c2) + 1 , charindex('|',c2) - charindex('=',c2) - 1) as int) d22,
      cast(substring(c2 , charindex('|',c2) + 1 , len(c2)) as int) d23,
      cast(substring(c3 , 1 , charindex('<',c3) - 1) as int) d31 ,
      cast(substring(c3 , charindex('|',c3) + 1 , len(c3)) as int) d32
    from
    (
      select parsename(replace(c,',','.'),3) c1,
             parsename(replace(c,',','.'),2) c2,
             parsename(replace(c,',','.'),1) c3
      from tb
    ) t
    ) m
    end
    godeclare @rtn as intEXECUTE my_proc 1, @rtn OUTPUT
    select @rtn
    /*
    ----------- 
    1(所影响的行数为 1 行)
    */EXECUTE my_proc 4, @rtn OUTPUT
    select @rtn
    /*
    ----------- 
    2(所影响的行数为 1 行)
    */EXECUTE my_proc 6, @rtn OUTPUT
    select @rtn
    /*
                
    ----------- 
    4(所影响的行数为 1 行)
    */drop proc my_proc
    drop table tb
      

  7.   


    --試試這個
    declare @s nvarchar(1000)
    set @s='x<=3|1,3<x<=5|2,5<x|4'select @s='case when '+replace(replace(replace(replace(@s,'|' , ' then ' ),',',' when ' ),'<x<','<x and x<'),'=x<','=x and x<')+' end'
    select @s='select  @out= ' + replace(@s,'x','@x')declare @x int,@out int
    exec sp_executesql @s,N'@x int,@out int output', 4, @out outputprint @out
    /*
    2
    */