How to get multiple column data in a comma separated string?

北战南征 提交于 2019-12-08 10:52:35

问题


I am getting data like

Result
------
 10
 23 
 21

But i want to get data in the following format.

Result
------
10, 23, 21

How to get that in a Query? Thanks in advance for any help :)


回答1:


Here is one way, There is a student table having studentName column with datatype as nvarchar(50) then following query will give you student names as comma separated values,

DECLARE @VALUES NVARCHAR(1000)
SELECT @VALUES = COALESCE(@VALUES + ',','') + CAST(STUDENTNAME AS NVARCHAR(50)) FROM STUDENT
SELECT @VALUES



回答2:


Sample code that doesn't use stored procedure :) ...

USE AdventureWorks
GO
-- Check Table Column
SELECT Name
FROM HumanResources.Shift
GO
-- Get CSV values
SELECT SUBSTRING(
(SELECT ',' + s.Name
FROM HumanResources.Shift s
ORDER BY s.Name
FOR XML PATH('')),2,200000) AS CSV
GO

More about it here:

SQL SERVER – Comma Separated Values (CSV) from Table Column

Edit:

For SQL-Server 2000, take a look here:

How to Format Query Result as Comma Separated Values (CSV)




回答3:


You can also check out: http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string




回答4:


In PostgreSQL:

SELECT company_id, array_to_string(array_agg(employee), ',') FROM mytable GROUP BY company_id;

from How to concatenate strings of a string field in a PostgreSQL 'group by' query?



来源:https://stackoverflow.com/questions/3371914/how-to-get-multiple-column-data-in-a-comma-separated-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!