表结构
字段1  字段2
001     张三
002     李四
003     小二
004     小三
......现在想用一条SQL语句生成这样的字符串
001:张三;002:李四;003:小二;004:小三.......
有什么好方法没有? 注意是一条SQL

解决方案 »

  1.   

    if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
    go
    create table #temp( [字段1] varchar(100), [字段2] varchar(100));
    insert #temp
    select '001','张三' union all
    select '002','李四' union all
    select '003','小二' union all
    select '004','小三' --SQL:
    SELECT STUFF((select ';' + [字段1] + ':' + [字段2]  from #temp FOR XML PATH('')),1,1,'')/*
    001:张三;002:李四;003:小二;004:小三
    */
      

  2.   

    create table #tb( [字段1] varchar(100), [字段2] varchar(100));
    insert #tb
    select '001','张三' union all
    select '002','李四' union all
    select '003','小二' union all
    select '004','小三' declare @s varchar(8000) 
    set @s=''
    select @s=@s+[字段1]+':'+[字段2]+';'
    from #tb
    set @s= left(@s,len(@s)-1)
    select @s/*
    001:张三;002:李四;003:小二;004:小三
    */