How to merge a field from multiple rows into one concatenated string

by Andrew Jackson 17. June 2006 16:31
Where you have multiple rows that you need to either display or report on as one single, concatenated field you can use the Coalesce function to merge them.

You can either do this in a stored procedure or create a function so it can be used inline in Select statements.

Below is an example of a function that will merge multiple policy numbers into one string containing them separated by commas.

CREATE FUNCTION dbo.fn_MergePolicyNums
(@HGNum as int)
RETURNS varchar(100) AS

BEGIN

declare @PolNums varchar(100) /* Holds multiple MEC numbers */

SELECT @PolNums = COALESCE (@PolNums + ', ' + PolicyNum, PolicyNum, @PolNums) FROM tblPolicy WHERE HGNum = @HGNum

RETURN ISNULL(@PolNums, '')
END

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Development | SQL

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen