如何使用sql server在单个列中转换多行 [英] how to convert multiple row in a single column using sql server
本文介绍了如何使用sql server在单个列中转换多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表emp,其中包含1列作为ID,表中有4条记录为1,2,3,4
当我运行命令select * from emp时结果是
ID
1
2
3
4
但我希望使用sql server以此格式转换结果。
ID:1,2,3,4
先谢谢。
i have a table emp which contain 1 column as ID and there is 4 record in table as 1,2,3,4
when i run command select * from emp Result is
ID
1
2
3
4
But i wants co convert result in this Format using sql server.
ID:1,2,3,4
Thanks in Advance.
推荐答案
试试这个:
Try this:
DECLARE @XYList AS varchar(MAX) -- Leave as NULL
SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(nvarchar(20), ID)+ ','
FROM emp
类似这个:
Something like this:
Select (Stuff((Select ', ' + FName From Accounts FOR XML PATH('')),1,2,''))
顺便说一句,你试过谷歌吗?我在几年前发布了以下链接:)
http://manasbhardwaj.net/get-column-values-as-comma-seperated-string/ [ ^ ]
如果你使用的是高于SQL2000版本,你可以使用FOR XML PATH.But如果你使用Sql2000。
是这样的:
If you are using is higher than the SQL2000 version, you can use FOR XML PATH.But if you Use Sql2000.
like this :
declare @s varchar(8000)
set @s = ''
select @s = @s + cloumnname + ',' from tablename where ...
set @s = stuff(@s,len(@s),1,'')
这篇关于如何使用sql server在单个列中转换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文