开发者

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

开发者 https://www.devze.com 2023-01-09 19:12 出处:网络
I am getting data like Result ------ 10 23 21 But i want开发者_StackOverflow中文版 to get data in the following format.

I am getting data like

Result
------
 10
 23 
 21

But i want开发者_StackOverflow中文版 to get data in the following format.

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

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


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)


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消