Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated values in one column - SQL SERVER

Tags:

sql

sql-server

Customer Table
--------------
ID   Name
1   James
2   Peter
Order Table
---------------
OrderId  CustId
100     1
101     1
102     2

How can I write a query that returns something like this

ID,Name,ListofOrders
1,James,"100,101"
2,Peter,"102"

In Sybase I had a function called LIST which I could use but I dont find a similar function in SQL SERVER

like image 553
JanetOhara Avatar asked Sep 15 '12 07:09

JanetOhara


People also ask

How do I get comma separated values in SQL Server?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.

Can we store comma separated values in SQL?

Multiple inputs to the same parameter can be accomplished with comma-separated values in the input parameter of the stored procedure or input to the tabular function, and used with the table in a T-SQL statement.


2 Answers

Please try:

select ID, [Name],
(select OrderID+',' from OrderTable where CustID=ID
group by OrderID for xml path('')) AS ListOfOrders
From CustomerTable
like image 156
TechDo Avatar answered Sep 18 '22 12:09

TechDo


Create a User Defined Function as shown below

CREATE FUNCTION [dbo].[CommaSeperatedOrderIDs](@CustId INT) returns varchar(Max)
AS  
BEGIN   

DECLARE @CommaSeperatedValues VARCHAR(MAX)
SELECT @CommaSeperatedValues = COALESCE(@CommaSeperatedValues+',' , '') + OrderID
FROM OrderTable WHERE CustId = @CustId
RETURN @CommaSeperatedValues

END

And then,

select ID, [Name], ([dbo].[CommaSeperatedOrderIDs](ID)) AS ListofOrders
From CustomerTable
like image 20
Kapil Khandelwal Avatar answered Sep 19 '22 12:09

Kapil Khandelwal