select时,条件这么写id in(3,9,10,1),想查询出来的id顺序也是3,9,10,1,而不是1,3,9,10这种,有什么办法吗?

解决方案 »

  1.   

    -- 可以想一个别名,按照制定的顺序硬编码一下,参考:
    select [id],alias = case [id] 
                when 3 then 1 
                when 9 then 2 
                when 10 then 3 
                when 1 then 4
                end 
    from yourTable
    order by alias  --- 按照别名排序
      

  2.   

    像这种如果查询时where条件比较少时,还行,如果比较多就麻烦了.
    除了这种其他的还有什么好的方式吗?
      

  3.   

    -- 拼凑字符,超烂方法(期待各位高手补充好方法!!!)
    -- 参考:
    declare @tmpTable table (val varchar(200)) -- 存储 in 条件临时表
    declare @val varchar(20), -- 获取in条件
    @stmt varchar(2000), -- 拼凑字符(when then)
    @tail varchar(2000),
    @sql varchar(2000), -- 准备执行之sql
    @i int -- 排序序列
    select @val = '',@sql = '',@stmt = '',@tail = '' ,@i = 1-- 插入条件数据(这里完全可以考虑用程序按照规则自动插入抛入in的值)
    insert into @tmpTable 
    select 3 union all
    select 9 union all
    select 10 union all
    select 11-- 利用游标获取查询条件值,开始拼凑字符
    declare cur cursor for
    select val from @tmpTable
    open cur
    fetch next from cur into @val
    while(@@fetch_status = 0)
    begin
    set @stmt = @stmt + ' when ' + @val + ' then ' + cast(@i as varchar) + ' '
    set @tail = @tail + @val + ','
    set @i = @i + 1
    fetch next from cur into @val
    end
    close cur
    deallocate curset @tail = left(@tail,len(@tail) - 1)
    set @sql = 'select [id] , alias = case seed '
    set @sql = @sql + @stmt + ' end from a where seed in (' + @tail + ') order by alias'
    print @sql -- 打印出来看看exec (@sql) -- 执行
      

  4.   

    刚才看了下,把上面的字段 seed 改成你的字段 [id],我没有注意改过来,就不再帖了。
      

  5.   

    ----创建测试数据
    declare @t table(id int)
    insert @t
    select 1 union all
    select 2 union all
    select 3 union all
    select 4 union all
    select 5 union all
    select 6 union all
    select 7 union all
    select 8 union all
    select 9 union all
    select 10----查询
    select * from @t where id in(3,9,10,1) 
    order by charindex(',' + rtrim(id) + ',',',' + '3,9,10,1' + ',')----或者
    declare @idlist varchar(20)
    set @idlist = '3,9,10,1'
    select * from @t where charindex(',' + rtrim(id) + ',',',' + @idlist + ',') > 0
    order by charindex(',' + rtrim(id) + ',',',' + @idlist + ',')
    /*结果
    id          
    ----------- 
    3
    9
    10
    1
    */