So this is a pretty standard requirement; I have a table containing address information, and I want to pull out one βformattedβ address with all the fields combined with comma delimiters.
The problem is that some fields may be NULL, and so I end up with commas. For example, one address could be β10 The Strand, Londonβ without any country at the end, but the next could be β5 Fleet Street, London, England.β If I select each address element and assume that it is always present, I would present these two addresses as:
"5 Fleet Street ,, London,
"10 The Strand ,, London, England"
Getting rid of extra commas from the middle is simple, just a test for NULL.
I know how to fix the problem with the final comma in two passes using CTE or a subquery, but can this be done in one pass through the data?
Here is an example of using CTE:
DECLARE @Address TABLE ( Name VARCHAR(255), Line1 VARCHAR(255), Line2 VARCHAR(255), Line3 VARCHAR(255), City VARCHAR(255), Country VARCHAR(255)); INSERT INTO @Address VALUES ('Complete', 'Test 1', 'Test 2', 'Test 3', 'Oxford', 'England'); INSERT INTO @Address VALUES ('Incomplete', '22 Accacia', NULL, NULL, 'York', 'England'); INSERT INTO @Address VALUES ('Missing End', '10 Bond Street', NULL, NULL, 'London', NULL); WITH Addresses AS ( SELECT CASE WHEN Name IS NULL THEN '' ELSE Name + ', ' END + CASE WHEN Line1 IS NULL THEN '' ELSE Line1 + ', ' END + CASE WHEN Line2 IS NULL THEN '' ELSE Line2 + ', ' END + CASE WHEN Line3 IS NULL THEN '' ELSE Line3 + ', ' END + CASE WHEN City IS NULL THEN '' ELSE City + ', ' END + CASE WHEN Country IS NULL THEN '' ELSE Country + ', ' END AS [Address] FROM @Address) SELECT LEFT([Address], LEN([Address]) - 1) AS [Address Clean] FROM Addresses;
What gives me:
Complete, Test 1, Test 2, Test 3, Oxford, England Incomplete, 22 Accacia, York, England Missing End, 10 Bond Street, London
Why do I need it? Partly because I cannot think of a way to do this, but βfeelingβ should be a way to get what I want, and partly because this request is executed through a linked server with a SQL 2000 mailbox, and therefore I cannot use CTE ( although I could easily rewrite the request using a sub request).