关于存储过程:在MySQL的所有行中首字母大写

Capitalize first letter in all rows MySQL

我需要一个脚本来运行,它将更新"给定名称"列并将所有首字母更改为大写。

我现在有这个代码……什么也没发生……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
DROP PROCEDURE IF EXISTS CAPITALIZE;
DELIMITER $$

CREATE PROCEDURE CAPITALIZE()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 1;
SELECT COUNT(*) INTO n FROM users;
-- SET n = (SELECT COUNT(*) FROM users);
SET i=0;
WHILE (i<=n) DO
  UPDATE users SET given_name = CONCAT( UPPER(SUBSTR(given_name,1,1)), SUBSTR(given_name,2)) WHERE user_id = n;
  UPDATE users SET last_name = CONCAT( UPPER(SUBSTR(last_name,1,1)), SUBSTR(last_name,2)) WHERE user_id = n;

  SET i = (i + 1);
END WHILE;
END $$
DELIMITER ;


正如@drew提到的,你最好对整个users表做一个全面的UPDATE声明:

1
2
3
UPDATE users
SET given_name = CONCAT( UPPER(SUBSTR(given_name,1,1)), LOWER(SUBSTR(given_name,2))),
    last_name = CONCAT( UPPER(SUBSTR(last_name,1,1)), LOWER(SUBSTR(last_name,2)))

要关闭安全更新模式,这将阻止上述查询工作,请键入以下命令:

1
SET SQL_SAFE_UPDATES = 0;

下面是一个工作的小提琴,演示了上述查询:

sqlfiddle