简体   繁体   中英

MySQL stored procedure or function to return a person's name in a specific format

I'm a little fuzzy on the difference between stored procedures and functions. I have an employee directory database with a data table containing, among other details, the following name fields:

first_name, varchar(45)
mi, char(3)
last_name, varchar(45)
suffix, varchar(10)

I'd like to be able to have a function/procedure return the full name in

last_name ( suffix ), first_name ( mi )

format, where the fields in parentheses are NULL optional in the table. I can build the formatted name string in PHP with

SELECT last_name, suffix, first_name, mi from employee;

, then use a series of conditionals to test for empty suffix and mi fields. But, I'd like to be able to use an SQL statement like

SELECT getDisplayName() WHERE last_name LIKE '%Smith%';

to return a result like

Smith III, John Q
Smith, Susanne L
Smithers, Waylon

Can someone point me in the right direction or at least tell me if I need a function or procedure?

thanks.

You can use this function:

DROP FUNCTION IF EXISTS getDisplayName;
DELIMITER $$
CREATE FUNCTION getDisplayName(last_name text, suffix text, first_name text, mi text)
  RETURNS TEXT
BEGIN
  DECLARE name text;
  SET name = '';
  IF last_name IS NOT NULL THEN
      SET name = last_name;
  END IF;

  IF suffix IS NOT NULL THEN
      SET name = CONCAT(name, ' ', suffix);
  END IF;

  IF first_name IS NOT NULL THEN
      SET name = CONCAT(name, ', ', first_name);
  END IF;

  IF mi IS NOT NULL THEN
      SET name = CONCAT(name, ' ', mi);
  END IF;

  RETURN name;
END;
$$
DELIMITER ;

So your select will look like:

SELECT getDisplayName(last_name, suffix, first_name, mi) FROM employee WHERE last_name LIKE '%Smith%';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM