1

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.

4 Answers 4

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not waiting for the best answer, I'm testing as they come in, and they're coming in fast. I'll respond as soon as I've finished testing and can confirm the correct one.
I've now tested this and can confirm that it works. It just needs a slight modification to add a comma after the housename. Thank you for your time in resolving this for me. Very much appreciated.
0

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

1 Comment

That will result in Banana House,29,Acacia Road... topicstarter asked for Banana House,29 Acacia Road...
0

How about this:

SELECT 
       housename
      ,CONCAT( housenumber, CONCAT(' ', COALESCE(address1, '')), CONCAT(' ', COALESCE(address2, '')), CONCAT(' ', COALESCE(address3, '')) ) AS address
      ,town
      ,postcode 
FROM tblAddress;

Comments

0

Try like below,

 SELECT CONCAT_WS ( ", ",
    housename,
    CONCAT(housenumber, CONCAT_WS (", ", NULLIF(address1, ''), NULLIF(address2, ''), NULLIF(address3, ''))),
    town,
    postcode) AS address
FROM tblAddress

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.