Using COALESCE to build string from a field of table
COALESCE is a very useful function, if you want to build a string of data from a field in a database table.
You can do the same with CURSOR and FETCH FROM, but COALESCE can do it way faster with less code.
Say, you have a table named Employee with following data under the field EmployeeName:
Bob
Joe
Sarah
Nicole
For some reason you want to have a variable that looks like this: Bob, Joe, Sarah, Nicole. With COALESCE you can do it very easy and fast:
DECLARE @EmpName varchar(100)
SELECT @EmpName = COALESCE(@EmpName + ', ', '') + CAST(EmployeeName AS varchar(100))
FROM Employee
If you do SELECT @EmpName you will get the result as mentioned above. Now, try to do that with CURSOR and FETCH FROM, you will be thankful that COALESCE is there.
For more reading, click here.









Leave your response!
You must be logged in to post a comment.