日期:2014-05-17  浏览次数:20565 次

能否用一条SQL,生成这样的数据格式?
表结构
字段1  字段2
001     张三
002     李四
003     小二
004     小三
......

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

------解决方案--------------------
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:小三
*/