How to Flatten a One to Many Into Comma Separated List in a Column (SQL Server)
This is a pretty short post, but I figure if I write it up here, I will remember it next time I need it. Every time I need this, I struggle to find it. The SQL below selects all the columns from the Claim Table, and then selects all the ErrorMessage from the ClaimValidationErrors table and creates a comma separated list that is stored in the ValidationErrors column. The STUFF command simply removes the redundant comma at the beginning of the list.
SELECT *,
STUFF((SELECT ',' + [ErrorMessage]
FROM [dbo].[ClaimValidationErrors] cve
WHERE cve.ClaimId = c.ClaimId
FOR XML PATH('')), 1, 1,'') ValidationErrors
FROM claims c
The ('') parameter on the FOR XML PATH removes the outer xml tag. So this is actually kind of a hack but it solves the problem.
I have yet to find a way to do this in Entity Framework with linq directly, so I usually create a view and add the view to my model so I can access it from my code.
Comments
Post a Comment