Concatenate strings within SQL
- April 20, 2015
In order to concatenate strings (delimited by with a string) from multiple rows in a SQL Table to a single field the Coalesce command is the one to use. Typically COALESCE is used to return a single field value which represents multiple rows concatenated by a string.
The output from the following would be something like 1,2, 3
The following example uses a function to return a joined table field with the primary data selected. The challenge was to return a single row from one table while returning values from the joined table into a single field. To accomplish this I used syntax similar to the following:
SELECT personID,dbo.fn_CombineValues(personID) Roles FROM [People]
The following function was created to support the above sql query. The function accepts the key to be used in the the joined table and returns a string value representing in this case the roles related to the primary table.