如何将SQL请求中的文本替换为ASCII字符组合?

时间:2015-09-01 04:12:52

标签: mysql sql text replace ascii

我想要的很简单:在表中有一个TEXT字段我希望将每个字符从ASCII [☺, ☻, ♥, ♦, ♣, ♠, ♂, ♀, ☼]数组转换为一个字符,转换尽可能简单:给定char为int,mod 9.在MySQL中这样的事情是否可行?如何做?

2 个答案:

答案 0 :(得分:1)

DROP FUNCTION IF EXISTS wtf;

DELIMITER | 
CREATE FUNCTION wtf( str TEXT ) RETURNS TEXT
BEGIN 

  DECLARE wtf_chars TEXT DEFAULT '☺☻♥♦♣♠♂♀☼';

  DECLARE i, len, wtf_len SMALLINT DEFAULT 1; 
  DECLARE ret TEXT DEFAULT '';
  DECLARE c CHAR(1);

  SET str       = CONVERT(str USING ascii); 
  SET len       = CHAR_LENGTH(str);
  SET wtf_len   = CHAR_LENGTH(wtf_chars); 

  REPEAT 
    BEGIN 
      SET c = MID(str, i, 1); 
      SET ret = CONCAT(ret, SUBSTRING(wtf_chars, (MOD(ASCII(c), wtf_len) + 1), 1)); 
      SET i = i + 1; 
    END; 
  UNTIL i > len END REPEAT; 

  RETURN ret; 

END | 
DELIMITER ;



SELECT wtf(`your_text_field`) FROM `your_table`;

答案 1 :(得分:0)

这只是一些指导原则,我只知道mysql的基础知识。

您需要set个变量
字符串函数substringasciiconcat
while循环

我不知道你如何在mysql中处理那些奇怪的array。帮助说阵列不存在。

col = '123456';
declare v_max int unsigned default 1000;
declare v_counter int unsigned default 1;
declare myChar varchar(1);
declare result varchar(100) default '';
declare myAscII  int;

-- get the lenth of the string
select CHAR_LENGTH(col) INTO v_max;

while v_counter < v_max do  
   -- get each char ascii  
   select ASCII(SUBSTRING(col, v_counter , 1)) INTO myAscII;

   -- get the array index 
   set myAscII = myAscII MOD 9;

   -- get the array value /*dont know how you handle this*/
   set myChar = WEIRD_ARRAY[myAscII]

   select CONCAT(result, myChar) into result;

   set v_counter = v_counter + 1;
end while;