有一个语句
select id from tablename order by id desc结果一般为
1
2
3
4
5
如果显示的结果是
1,2,3,4,5

解决方案 »

  1.   

    declare @temp varchar(1000)
    set @temp = ''
    select @temp = @temp + id 
    from tablename 
    order by id desc
    select @temp
      

  2.   

    /*如何将一列中所有的值一行显示
    数据源
      a
      b
      c
      d
      e
    结果
    a,b,c,d,e
    */create table tb(col varchar(20))
    insert tb values ('a')
    insert tb values ('b')
    insert tb values ('c')
    insert tb values ('d')
    insert tb values ('e')
    go--方法一
    declare @sql varchar(1000)
    set @sql = ''
    select @sql = @sql + t.col + ',' from (select col from tb) as t
    set @sql='select result = ''' + left(@sql , len(@sql) - 1) + ''''
    exec(@sql)
    /*
    result     
    ---------- 
    a,b,c,d,e,
    */--方法二
    declare @output varchar(8000)
    select @output = coalesce(@output + ',' , '') + col from tb
    print @output
    /*
    a,b,c,d,e
    */drop table tb
      

  3.   

    create table tb(id int)
    insert into tb select 1 union all select 2 union select 3 union select 4 union select 5
    go
    select stuff((
    select ','+convert(varchar,id) from tb for xml path('')
    ),1,1,'')
    go
    drop table tb
    /*
    ---------------------------------------------------------------------------------
    1,2,3,4,5*/