I always have a preference for doing as much processing in SQL as possible. In this scenario, I needed to get the address out of a database in one line. The data was stored in multiple fields (one per line), some of which may be empty or null.
create FUNCTION [dbo].[udf_concat_fields]
(@add1 varchar(255), @add2 varchar(255))
RETURNS varchar(512)
AS
BEGIN
declare @catadd varchar(512)
set @catadd = case isnull(@add1, '')
when '' then ''
else @add1 + ', '
end +
case isnull(@add2, '')
when '' then ''
else @add2
end
if (right(@catadd, 2) = ', ')
set @catadd = left(@catadd, len(@catadd)-1) --clean out unnecessary commas at end of the line
return (@catadd)
END
The function can then be called recursively
select dbo.udf_concat_fields(dbo.udf_concat_fields(dbo.udf_concat_fields(company_add1, company_add2), company_add3), company_add4) as 'Address'
from tblAddress
to return a correctly formatted address in one field.