SQL COALESCE Command Features

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.

DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList

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.

CREATE FUNCTION fn_CombineValues
     @FK_ID INT --The foreign key from TableA which is used to fetch corresponding records
 DECLARE @SomeColumnList VARCHAR(8000);
 SELECT @SomeColumnList = COALESCE(@SomeColumnList + ', ', '') + CAST(Role AS varchar(20)) 
 FROM dbo.SA_PeopleRoles C
 INNER JOIN dbo.SA_Roles r ON r.roleid=c.RoleID
: 8pt; overflow: visible; border-style: none; padding: 0px;"> WHERE C.personID = @FK_ID;
 SELECT @SomeColumnList




comments powered by Disqus


Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F