mysql:触发每个单词的首字母大写

kokeuurv  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(514)

伙计们,
我有一张table,里面有:

CREATE TABLE IF NOT EXISTS `people` (
`Id_People` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`Firstname` varchar(20) NOT NULL,
`Lastname` varchar(20) NOT NULL,
PRIMARY KEY (`Id_People`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1002 ;

如何设置将我的名字和姓氏的第一个字母大写的触发器?
每当我加上一个人,
在插页上:

INSERT INTO people (Firstname, Lastname) VALUES ('doe', 'john')

每当我编辑某人时,
更新时:

UPDATE people SET Lastname = 'smith', Firstname= 'jane' WHERE Id_People = 1;

还有这个连一个双筒的名字,比如:约翰·史密斯(名字)多伊(姓氏)?

7fyelxc5

7fyelxc51#

我可以建议您使用mysql rdbms。
mysql不提供每个单词首字母大写的标准函数。
首先,
创建此函数:

DELIMITER $$
CREATE FUNCTION `capitalize`(s varchar(255)) RETURNS varchar(255) 
BEGIN
  declare c int;
  declare x varchar(255);
  declare y varchar(255);
  declare z varchar(255);

  set x = UPPER( SUBSTRING( s, 1, 1));
  set y = SUBSTR( s, 2);
  set c = instr( y, ' ');

  while c > 0
    do
      set z = SUBSTR( y, 1, c);
      set x = CONCAT( x, z);
      set z = UPPER( SUBSTR( y, c+1, 1));
      set x = CONCAT( x, z);
      set y = SUBSTR( y, c+2);
      set c = INSTR( y, ' ');     
  end while;
  set x = CONCAT(x, y);
  return x;
END$$

其次,
为更新和插入创建触发器

CREATE TRIGGER frst_l_up_insert BEFORE INSERT ON people FOR EACH ROW
SET NEW.Firstname = capitalize(NEW.Firstname), NEW.Lastname = capitalize(NEW.Lastname);

CREATE TRIGGER frst_l_up_update BEFORE UPDATE ON people FOR EACH ROW
SET NEW.Firstname = capitalize(NEW.Firstname), NEW.Lastname = capitalize(NEW.Lastname)

最后,
更新表中的现有记录

UPDATE people SET Lastname = capitalize(Lastname), Firstname = capitalize(Firstname);

相关问题