2012-08-12 221 views
0

我已经创建了这个小函数(类似于oracle的替代函数),它对大多数字符都适用,但我无法弄清楚它为什么不能替代空格...MySQL的等价物Oracle的SUBSTITUTE函数 - 空间替换问题

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

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 ; 

回答

0

在MySQL中已经有一个REPLACE功能:

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

这不就是你想要什么?

+0

嗨dyyyy这使用替换,但对于多个字符不只是当时的一个普通替换...但它不占用空间的某种原因 – Leo 2012-08-12 13:16:13