¿Cómo obtener valores separados por comas en SQL Server?

Tengo dos mesas llamadas tblEmployee y tblWorkPlace. The second table consists of multiple rows for each employee. I want to get the result as follows

EmployeeName   WorkPlace
Gopi           India,Pakistan,...

Es decir, si tblWorkPlace consists of multiple rows for an employee, I want the result in a single row, with data being separated by commas.

How will I get this result ????

preguntado el 09 de marzo de 12 a las 15:03

¿Qué versión de SQL Server, por favor? -

4 Respuestas

You'll need to have code on the client side for this. It is possible to make this happen in sql server, but it's not trivial, the performance is horrible, and this kind of thing does not belong on the database de todos modos.

respondido 09 mar '12, 15:03

For small reports, this is not a big deal in SQL. Performance is NOT an issue, if you code it properly. - Dios de datos

You're not very clear on how the tables tblWorkplace y tblEmployee are connected - I'm assuming by means of a many-to-many link table or something.

If that's the case, you can use something like this:

SELECT
    e.EmpName, 
    (SELECT STUFF(
        (SELECT ',' + w.WPName
         FROM @Workplace w 
         INNER JOIN @WorkplaceEmployeesLink we ON w.WorkplaceID = we.WorkplaceID
         WHERE we.EmpID = e.EmpID
         FOR XML PATH('')
        ), 1, 1, '')
    ) AS Workplaces
FROM @Employee e

(I've replaced your tables with my own table variables @Employee y @Workplace etc. for testing)

Esto me da una salida algo como:

EmpName  Workplaces
Gopi     India,Pakistan

for that one row.

Basically, the internal FOR XML PATH('') selects the list of workplaces for each employee, and prepends each workplace with a ',' so you get something like ,India,Pakistan.

El STUFF method then stuff an empty string into that resulting string, at position one, for a length of 1 - essentially wiping out the first comma, thus you get the list of workplaces as you desired.

respondido 09 mar '12, 15:03

You can assign multiple values to a variable in a select statement. I call this "flattening" the records.

declare @WorkPlace varchar(max)
select @WorkPlace = ''  -- it is important to be NOT null

select @WorkPlace = @WorkPlace + WorkPlace + ', '
  from YourTable
 where EmployeeName = 'Gopi'

You may want to add some code to remove the final ',' from the string.

respondido 09 mar '12, 15:03

That is true. I would not use this technique on large datasets. - Dios de datos

respondido 26 mar '12, 21:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.