简体   繁体   English

MySQL存储过程或函数以特定格式返回人的名字

[英]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 ) 姓氏后缀 ), 姓氏mi

format, where the fields in parentheses are NULL optional in the table. 格式,其中括号中的字段在表中为NULL可选。 I can build the formatted name string in PHP with 我可以使用以下命令在PHP中构建格式化的名称字符串

SELECT last_name, suffix, first_name, mi from employee;

, then use a series of conditionals to test for empty suffix and mi fields. ,然后使用一系列条件测试空后缀和mi字段。 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%';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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