小编典典

计算字符串中的大写字母

sql

如何使用MySQL查询来计算大写字母?我现在正在尝试

COUNT(IF(MATCH(post_text) AGAINST('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'),1,NULL))

但这给我一个错误的说法:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U' at line 4

我猜,我不允许在AGAINST子句中使用列表,这很烂

那么,有没有办法实现这一目标?


阅读 214

收藏
2021-04-14

共1个答案

小编典典

试试这个功能-

DELIMITER $$

CREATE FUNCTION cnt_up_case(str VARCHAR(255))
RETURNS VARCHAR(255)
NOT DETERMINISTIC
CONTAINS SQL
BEGIN

  SET @cnt = 0;
  SET @len = length(str);
  SET @i = 1;

  WHILE @i <= @len
  DO
    SET @c = substring(str, @i, 1);
    IF ascii(@c) > 64 AND ascii(@c) < 91 THEN
      SET @cnt = @cnt + 1;
    END IF;

    SET @i = @i + 1;
  END WHILE;

  RETURN @cnt;
END
$$

DELIMITER ;

例子:

SET @Param1 = 'AbCdE';
SET @ResultValue = cnt_up_case(@Param1);
SELECT @ResultValue;
--------------
3
2021-04-14