Reputation: 31
I have a database which basically holds addresses
The table (tblAddress) looks like this...
housename | housenumber | address1 | address2 | address3 | town | postcode
Banana House | 29 | Acacia Road | Yellow Skin Way | | Nuttytown | W1 1MP
When I search the database based on a postcode I want to be able to return and result like this...
Banana House,29 Acacia Road,Yellow Skin Way,Nuttytown,W1 1MP
So I need the housenumber concatenated with address1 IF address1 is populated. If not then concat with address2 or address3. Then the rest of the address to follow as per the example.
I tried using IF and CASE statements but can't seem to get anywhere near the output I'm after.
Hope that makes sense.
Upvotes: 1
Views: 342
Reputation: 5912
You can do it by adding few concat operations.
Check below code it should work.
SELECT CONCAT(housename, CONCAT(" ",CONCAT(housenumber, CONCAT(" ",CONCAT_WS(' ,',
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')))))) AS concatedAddress FROM tblAddress;
Upvotes: 2
Reputation: 1520
Try like below,
SELECT CONCAT_WS ( ", ",
housename,
CONCAT(housenumber, CONCAT_WS (", ", NULLIF(address1, ''), NULLIF(address2, ''), NULLIF(address3, ''))),
town,
postcode) AS address
FROM tblAddress
Upvotes: 0
Reputation: 1356
How about this:
SELECT
housename
,CONCAT( housenumber, CONCAT(' ', COALESCE(address1, '')), CONCAT(' ', COALESCE(address2, '')), CONCAT(' ', COALESCE(address3, '')) ) AS address
,town
,postcode
FROM tblAddress;
Upvotes: 0
Reputation: 2768
Use concat_ws()
(concatenation with separator) along with nullif()
SELECT CONCAT_WS(',', NULLIF(housename, ''),
NULLIF(housenumber, ''),
NULLIF(address1, ''),
NULLIF(address2, ''),
NULLIF(address3, ''),
NULLIF(town, ''),
NULLIF(postcode, '')
) AS address FROM tblAddress
Upvotes: 0