举个例子说明:
select * from table1 where 字段1 like ''c''
这个查询执行后,所有饱含‘a’的记录都会检索出来,例如ac,bac,cd,c等,如果按照字段1进行排序,可能的顺序就是
ac
bac
c
cd现在我希望实现的功能是:如果查询条件是‘c’,那么‘c’就排在最前面,也就是结果中,越相近的越考前,例如,‘c’就比‘ac’考前,而‘ac’又比‘bac’靠前请问有办法实现吗?

解决方案 »

  1.   

    这个有点接近
    select * from table1 where 字段1 like '%c%' order by len(字段1) asc
      

  2.   


    更正LZ一个问题:select * from table1 where 字段1 like ''c'' 
    --等价于
    select * from table1 where 字段1=''c''
      

  3.   

    --建立测试环境
    set nocount on
    create table test(f varchar(20))
    insert into test select 'ac'
    insert into test select 'bac'
    insert into test select 'c'
    insert into test select 'cd'
    go
    --测试
    select * from test
    where f like '%c%'
    order by charindex('c',f)--删除测试环境
    drop table test
     set nocount off
      

  4.   

    select * from table1 where 字段1 like '%c%' order by charindex('c',字段1)
      

  5.   

    select * from table1 where JC like ''%'+edtJC.Text+'%'' order by charindex(edtJC.Text,JC)
    这样做出错,提示为:列前缀‘edtJC’与查询中所用的表名或别名不匹配,,,,
    是不是不能使用变量??
      

  6.   

    'select * from table1 where JC like ''%'+edtJC.Text+'%'' order by charindex('''+edtJC.Text+''',JC)'
      

  7.   

    'select * from table1 where JC like ''%'+edtJC.Text+'%'' order by charindex('''+edtJC.Text+''',JC) '
      

  8.   

    没错了,不过,这个函数没实现我想要的功能,抱歉是我没说清楚,我的意思是:
    当输入‘a’的时候,可能会查询出‘a','ab','dab',等等,我希望'a'是排在最前面的,'ab'在其次,'dba'在最后,也就是说,和输入的越相似越靠前
      

  9.   

    另外,internetroot兄弟的方法我也试过了,在sqlsever里直接使用是可以生效的,但是在程序中使用却没效果,奇怪啊,,,
      

  10.   

    jinjazz这位大侠的可以实现你的效果了
      

  11.   

    'select * from table1 where JC like ''%'+edtJC.Text+'%'' order by charindex('''+edtJC.Text+''',JC),len(JC)'
      

  12.   

    charindex是返回字符串在另一个字符串中的起始位置,我觉得不适用这里,举个例子:
    输入的是'a',选出的记录有'da''abcde',正确的排序应该是'da','abcde',如果使用charindex,排序就会成为'abcde','da',因为'a'在'ba'中的起始位置是1,而在'abcde'中的起始位置是0
      

  13.   

    那碰到aaaaaaaa呢?当然也不能用长度了
      

  14.   

    终于查明了,是我自己在查询后又适用sort做了一次排序,实在是太菜了,抱歉啊,谢谢大家!
      

  15.   

    在sqlserver中测试如下语句--建立测试环境
    set nocount on
    create table test(f varchar(20))
    insert into test select 'acdf'
    insert into test select 'bac'
    insert into test select 'csffa'
    insert into test select 'cd'
    go
    --测试--建立自定义函数,返回相似程度
    create function f_getcount(@c varchar(1000),@str varchar(8000))
    returns float
    as
    begin
    declare @ret float
    declare @step int
    declare @temp varchar(8000)
    set @temp=replace(@str,'_','%')
    set @temp=replace(@temp,@c,'_')

    set @ret=0
    set @step=0
    while @step<=len(@temp)
    begin
    set @step=@step+1
    if substring(@temp,@step,1)='_'
    set @ret=@ret+1
    end
    set  @ret=@ret*len(@c)/len(@str)
    return @ret
    end
    goselect * from test
    where f like '%a%'
    order by dbo.f_getcount('a',f) desc
     --删除测试环境
    drop table test
    drop function f_getcount
     set nocount off--结果
    /*
    bac
    acdf
    csffa
    */