SQL COALESCE Command Features

posted on Monday, August 24, 2009 5:37 PM

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:

i.e.

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
 )
 RETURNS VARCHAR(8000)
 AS
 BEGIN
 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
 WHERE C.personID = @FK_ID;
 
 RETURN 
 (
 SELECT @SomeColumnList
 )
 END

References:http://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value

category: SQL

Comments


# re: SQL COALESCE Command Features
Posted by bin on 8/25/2009 4:19 PM
Gravatar in SQL 2005 and above use XML statement, is more handy
# re: SQL COALESCE Command Features
Posted by Keno spielen on 3/25/2010 1:36 AM
Gravatar I want to suggest that look at the execution plans generated between the two. My first guess is that with coalesce in the where, it generates a less efficient plan due to missing indexes, the database tuning wizard can often give you a good idea what needs to be added
.
Post Comment
Title *
Name *
Email
Url
Comment *
Please add 6 and 2 and type the answer here:

About Me

An engineer by training and a software developer at heart. My techniques and approaches meld engineering approaches with software technology.

Core to these principles is a systematic approach to the development of software with a strong lifecycle and process management emphasis through adoption of mature technologies.

Ten years designing heavy structural steel and concrete structures and 12 years in the software development profession have embedded strong project management and business knowledge in my approaches.

Subscribe to Rss Feed


Follow me on twitter @dyardy