MySQL相当于Oracle的SUBSTITUTE函数 - 空间替换问题

时间:2012-08-12 13:05:52

标签: mysql function substitution

我已经创建了这个小函数(类似于oracle的替换函数),它适用于大多数字符,但我无法弄清楚它为什么不替换空格...

有人可以对此有所了解吗?

DROP FUNCTION IF EXISTS MPT_FUNC_SUBSTITUTE;
DELIMITER // 
CREATE FUNCTION MPT_FUNC_SUBSTITUTE
(
  p_in_str          VARCHAR(1000),
  p_substitute_from VARCHAR(100),
  p_substitute_to   VARCHAR(100)
) 
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
#--+==============================================================================+
#--| Name        : MPT_FUNC_SUBSTITUTE                                            |
#--|                                                                              |
#--| Description : Designed to search for platinum ads.                           |
#--|                                                                              |
#--| Parameters  : p_in_str          [Mandatory] - The string to modify.          |
#--|               p_substitute_from [Mandatory] - Susbtitute from string         |
#--|               p_substitute_to   [Mandatory] - Susbtitute to string           |
#--|                                                                              |
#--| Returns     : p_out_str                                                      |
#--|                                                                              |
#--| Author             Date        Version   Remarks                             |
#--| ------------------ ----------- --------- ----------------------------------- |
#--| Leo Coppens        12-Aug-2012 1.0       Created                             |
#--|                                                                              |
#--+==============================================================================+

#-- DECLARE statements
  DECLARE lc_api_name   VARCHAR(30)   DEFAULT 'MPT_PROC_SEARCHDEALERS';
  DECLARE i             INT           DEFAULT 1;
  DECLARE chr1,chr2     CHAR(1);
  DECLARE p_out_str     VARCHAR(1000) DEFAULT p_in_str;

#-- Program Logic

  #-- Do the replacement if the necessary values are provided
  IF     p_in_str          IS NOT NULL
     AND p_substitute_from IS NOT NULL
  THEN
    SET p_out_str = p_in_str;
    #-- Start the replacement loop
    WHILE i <= CHAR_LENGTH(p_substitute_from) 
    DO
      #-- Get the characters to replace from and to
      SET chr1 = SUBSTR(p_substitute_from, i, 1);
      SET chr2 = IFNULL(SUBSTR(p_substitute_to, i, 1),'');
      #-- Do the replacement now
      SET p_out_str = REPLACE(p_out_str, chr1, chr2);
      #-- Increase i to continue the loop
      SET i = i + 1;
    END WHILE; 

  RETURN p_out_str;
  END IF;

END //

DELIMITER ;

1 个答案:

答案 0 :(得分:0)

在MySql中已经有一个REPLACE函数:

SELECT REPLACE('www.mysql.com', 'w', 'Ww');

这不是你想要的吗?

相关问题