Skip to content

Instantly share code, notes, and snippets.

@Godoy
Created January 21, 2013 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Godoy/4588735 to your computer and use it in GitHub Desktop.
Save Godoy/4588735 to your computer and use it in GitHub Desktop.
Select, separated by commas, the fields in a many-to-many relationship
SELECT DISTINCT Cadastro.id, Cadastro.nome,
STUFF(
(SELECT ', ' + Area.nome
FROM Area_Cadastro, Area
WHERE Cadastro.ID = Area_Cadastro.cadastro_id AND Area_Cadastro.area_id = Area.id
FOR XML PATH (''))
, 1, 1, '') AS areas
FROM Cadastro
LEFT JOIN Area_Cadastro ON (Cadastro.ID = Area_Cadastro.cadastro_id)
LEFT JOIN Area ON (Area_Cadastro.area_id = Area.id)
GROUP BY Cadastro.id, Cadastro.nome, Area.nome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment