I recently had the problem that I needed to format addresses for mailing envelopes. The address data was pretty badly bunged up, so I (re)invented this little gem.
If any field is missing, the field as well as any surrounding formatting will disappear. This behavior works for NULL and empty (”) fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | delimiter // CREATE FUNCTION KE_IC.format_us_address(prefix text,firstname text,mi text,lastname text,suffix text, company text, address1 text,address2 text,city text,state text,zip text) RETURNS text CHARACTER SET utf8 COMMENT 'uses null propagation to format us addresses' BEGIN # Elements AND separators are ONLY displayed WHEN present # treat empty FIELDS AS NULLS RETURN CONCAT_WS('\r\n',CONCAT_WS(', ',CONCAT_WS('. ', IF (prefix='',NULL,prefix),CONCAT_WS(' ', IF(firstname='',NULL,firstname),CONCAT_WS('. ', IF(mi='',NULL,mi), IF(lastname='',NULL,lastname)))),IF(suffix='',NULL,suffix)), IF(company='',NULL,company), IF(address1='',NULL,address1), IF(address2='',NULL,address2), CONCAT_WS(' ', IF(city='',NULL,city),CONCAT_WS(', ',IF(state='',NULL,state),IF(zip='',NULL,zip))), 'USA' ); #format_us_address('Mr','George','M','Cohen',NULL,NULL,'123 Main St.',NULL,'Anytown','CA','89754'); #results: #Mr. George M. Cohen #123 Main St. #Anytown CA, 89754 #notice the lack OF company, address2 line # AND the lack OF sep FOR non-existent suffix END // delimiter ; SELECT format_us_address('Mr','George','M','Cohen',NULL,NULL,'123 Main St.',NULL,'Anytown','CA','45647'); |