SoFunction
Updated on 2025-03-09

MySql determines the specific functions of Chinese characters, dates, and numbers

Several commonly used mysql functions, and the specific functions of MySql to judge Chinese characters, dates, and numbers are shared with you. The specific content is as follows

1. Determine whether the string is a Chinese character. Return value: 1-Chinese character 0-Non-Chinese character

DROP FUNCTION IF EXISTS fc_is_hanzi;

CREATE FUNCTION fc_is_hanzi(
p_str VARCHAR(1024)
)
  RETURNS int(11)
  NOT DETERMINISTIC
  SQL SECURITY DEFINER
  COMMENT 'Check whether the string is Chinese character'
BEGIN
/* Check whether the string is a Chinese character Return value: 1-Chinese character 0-Non-Chinese character*/

  DECLARE _ret, i, other_cnt, l_acode INT DEFAULT 0;
  SET _ret = 0;
  SET i = 1;
  SET other_cnt = 0;
  SET l_acode = 0;
  WHILE i <= CHAR_LENGTH(p_str) DO
    SET l_acode = ASCII(SUBSTRING(p_str, i, 1));
    IF l_acode<124 or l_acode>254 THEN
      SET other_cnt = other_cnt + 1;
    END IF;
    SET i = i + 1;
  END WHILE;
  IF other_cnt = 0 THEN
    SET _ret = 1;
  ELSE
    SET _ret = 0;
  END IF;
  RETURN _ret;
END;

2. Determine whether the date format is correct (return value: 1-correct 0-error)

DROP FUNCTION IF EXISTS fc_ck_date;

CREATE FUNCTION fc_ck_date(
p_cont CHAR(32) 
)
  RETURNS tinyint(4)
  NOT DETERMINISTIC
  SQL SECURITY DEFINER
  COMMENT 'Determine whether the date format is correct'
BEGIN
/*Determine whether the date format is correct (return value: 1-correct 0-error)*/
/*The input value format is: yyyyMMdd or yyyy-MM-dd*/

IF(SELECT DATE_FORMAT(p_cont,'%Y%m%d')) IS NULL THEN
  RETURN 0;
ELSE
  RETURN 1;
END IF;

END;

3. Determine whether the string is a pure number (return value: 1-a pure number 0-a non-pure number)

DROP FUNCTION IF EXISTS fc_is_num;

CREATE FUNCTION fc_is_num(
p_string VARCHAR(32) 
)
  RETURNS int(4)
  NOT DETERMINISTIC
  SQL SECURITY DEFINER
  COMMENT 'Check if the string is a pure number'
BEGIN
/* Check if the string is a pure number*/
/*Return value: 1-is a pure number 0-is a non-non-is a pure number*/

   DECLARE iResult INT DEFAULT 0;
   SELECT p_string REGEXP '^[0-9]*$' INTO iResult;
   IF iResult = 1 THEN
    RETURN 1;
   ELSE
     RETURN 0;
   END IF;
END;

The above are the three functions of MySql to judge Chinese characters, dates and numbers. I hope it will be helpful to everyone's learning.