2011-10-14 108 views
1

我有一個table1的MySQL存儲功能

tid letter1 letter2 
1 a  e 
2 p  b 
3 c  k 
4 pp  bb 
5 rr  ll 

和另一表2

t2id word 
1 banana 
2 strawberry 
3 apple 
4 grape 

我需要一個MySQL功能的替換之後,比較與來自表2的單詞的輸入單詞在表1上處理,如:

SELECT CHAR_LENGTH(word) AS charl FROM table2; 

DECLARE i INT DEFAULT 0; 

SET query = CONCAT(
    ' SELECT word FROM table2 WHERE (', 
    WHILE i < charl DO 
     //if word's i'nth letter found in the table1 
     IF (SELECT letter2 FROM table1 WHERE word{i} = letter1) 
     //replace letter1 with letter2 on this row 
     'REPLACE(word,letter1,letter2) AND ', 
    END; 
    ') = 'inputword' '; 

我的mysql知識很差這樣做。我怎樣才能做到這一點?

回答

0

正如你猜測你需要在存儲過程中這樣做。

實際上存儲功能:

DELIMITER $$ 

CREATE FUNCTION ReplaceChars(Fullword VARCHAR(255) 
          , ReplaceThis VARCHAR(255) 
          , WithThis VARCHAR(255)) RETURNS VARCHAR(255) 
BEGIN 
    DECLARE Result VARCHAR(255); 
    DECLARE i INTEGER;  

    SET Result = Fullword; 
    IF LENGTH(ReplaceThis) = LENGTH(WithThis) THEN 
    SET i = LENGTH(ReplaceThis); 
    WHILE i > 0 DO 
     SET Result = REPLACE(Result, MID(ReplaceThis,i,1),MID(WithThis,i,1)); 
     SET i = i - 1; 
    END WHILE; 
    END IF; 
    RETURN Result; 
END $$