You can use ISNULL
(or COALESCE
if you prefer)
select
ISNULL(Address1 + char(13) + char(10), '') +
ISNULL(Address2 + char(13) + char(10), '') + ...
from @tbl
(Because NULL + something is still NULL)
Pregunta
Please consider the following table that holds address details for people:
DECLARE @tbl TABLE
(
userId int IDENTITY(1,1),
address1 nvarchar(100),
address2 nvarchar(100),
address3 nvarchar(100),
addressTown nvarchar(100),
addressCounty nvarchar(100),
addressPostCode nvarchar(10)
);
INSERT INTO
@tbl (address1, address2, address3, addressTown, addressCounty, addressPostCode)
VALUES
('1 Some Road', 'High Hill', 'Battersea', 'London', NULL, 'SW1 2AB'),
('54 Main Street', 'Lowville', NULL, 'Sometown', 'Cumbria', 'AB12 3BA');
SELECT * FROM @tbl;
The output shows this:
userId address1 address2 address3 addressTown addressCounty addressPostCode
----------- --------------- -------------- ------------- ---------------- ------------- ---------------
1 1 Some Road High Hill Battersea London NULL SW1 2AB
2 54 Main Street Lowville NULL Sometown Cumbria AB12 3BA
However, I'd like to concatenate all of the address fields into a single field for the purpose of this statement, so that the results appear as follows:
userId Address
----------- --------------------
1 1 Some Road
High Hill
Battersea
London
SW1 2AB
2 54 Main Street
Lowville
Sometown
Cumbria
AB12 3BA
Please note that this is NOT the same problem as concatenating rows in a single column (using XML etc)!
I have done this using the following approach, but it seems like a whole lot of code for such a small task:
SELECT
userId,
CASE WHEN address1 IS NOT NULL THEN
address1 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN address2 IS NOT NULL THEN
address2 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN address3 IS NOT NULL THEN
address3 + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressTown IS NOT NULL THEN
addressTown + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressCounty IS NOT NULL THEN
addressCounty + CHAR(13) + CHAR(10)
ELSE ''
END +
CASE WHEN addressPostCode IS NOT NULL THEN
addressPostCode + CHAR(13) + CHAR(10)
ELSE ''
END as [Address]
FROM
@tbl
Is there a better/faster/more recommended way to achieve this?
Solución
You can use ISNULL
(or COALESCE
if you prefer)
select
ISNULL(Address1 + char(13) + char(10), '') +
ISNULL(Address2 + char(13) + char(10), '') + ...
from @tbl
(Because NULL + something is still NULL)
Otros consejos
Thanks to @podiluska's input, here is the final answer that also ensures NULLs are returned if the entire concatenated address is still NULL:
SELECT
userId,
NULLIF(ISNULL(address1 + CHAR(13) + CHAR(10), '') +
ISNULL(address2 + CHAR(13) + CHAR(10), '') +
ISNULL(address3 + CHAR(13) + CHAR(10), '') +
ISNULL(addressTown + CHAR(13) + CHAR(10), '') +
ISNULL(addressCounty + CHAR(13) + CHAR(10), '') +
ISNULL(addressPostCode + CHAR(13) + CHAR(10), ''), '') as [Address]
FROM
@tbl;