0

when selecting a customers name from a table the database should call a function that formats the name to

lastname, firstname

The function I created is

CREATE DEFINER=`root`@`localhost` FUNCTION `FORMAT_NAME`(firstname VARCHAR(25), lastname VARCHAR(25)) RETURNS varchar(50) CHARSET utf8 RETURN CONCAT(lastname, ', ', firstname) 

Within my SELECT I can now write

SELECT FORMAT_NAME(customer.firstname, customer.lastname) as Name 

and this returns me

Doe, John

Normally I would solve this by code but I have to use a FUNCTION and have to set up default variables.

How can I define default variables here if a value is empty or null or just not correct?

1 Answer 1

1

You just need to use the COALESCE function :

CREATE DEFINER=`root`@`localhost` FUNCTION `FORMAT_NAME`(firstname VARCHAR(25), lastname VARCHAR(25)) RETURNS varchar(50) CHARSET utf8 RETURN CONCAT(COALESCE(lastname, 'myDefaulValueName'), ', ', COALESCE(firstname, 'myDefaultValueFName')) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.