Mysql函数,用于查询表并从查询结果中重构字符串

时间:2015-05-08 17:23:54

标签: mysql sql function

我是mysql编程的新手,我会用字符串参数创建一个mysql函数 myFunction ;查询表并从查询结果重建字符串,如下例所示:

myTable
 ---------------
|id   |  value   |
 ---------------
| id1 |value1    |
| id2 |value2    |
| id3 |value3    |
| id4 |value4    |
 ---------------

调用此函数就像这样

myFunction('value2#value1#value4')

并且必须返回

 'id2#id1#id4'

1 个答案:

答案 0 :(得分:0)

检查SQL Fiddle

我的表

-- the table def
create table myTable (id char(3), value char(6));
insert into myTable values( 'id1', 'value1');
insert into myTable values( 'id2', 'value2');
insert into myTable values( 'id3', 'value3');
insert into myTable values( 'id4', 'value4');

获取特定ID

-- get Id by Value
CREATE function getIdByValue( theValue TEXT ) 
RETURNS TEXT READS SQL DATA
BEGIN
  DECLARE theId TEXT;
  DECLARE ok INT DEFAULT FALSE;
  DECLARE crs CURSOR FOR 
    SELECT id FROM myTable where value = theValue;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET ok = TRUE;

  SET theId = '';

  OPEN crs;
  read_loop: LOOP
    FETCH crs INTO theId;
    IF ok THEN
      LEAVE read_loop;
    END IF;
  END LOOP;
  CLOSE crs;
  RETURN theId;
END//

您描述的MyFunction

-- the myFunction, usage: myFunction('value2#value1#value4')
CREATE function myFunction( v TEXT )
RETURNS TEXT READS SQL DATA
BEGIN
  DECLARE theId TEXT;
  DECLARE theIds TEXT;
  DECLARE theValue TEXT;
  DECLARE vInstr INT;

  SET theId  = '';
  SET theIds = '';

  v_loop: LOOP

    SET vInstr = INSTR(v,'#');
    IF vInstr = 0 THEN
      SET theValue = v;
      SET theId = getIdByValue(theValue);
    ELSE
      SET theValue = SUBSTRING(v, 1, vInstr-1);
      SET v = SUBSTRING(v, vInstr+1);
      SET theId = concat( getIdByValue(theValue), '#');
    END IF;

    SET theIds = CONCAT(theIds, theId);

    IF vInstr = 0 THEN
      LEAVE v_loop;
    END IF;

  END LOOP; 

  RETURN theIds;
END//

致电

SELECT myFunction( 'value2' );
SELECT myFunction( 'value2#value4' );
SELECT myFunction( 'value2#value4#value1' );
SELECT myFunction( 'value2#value4#value1#value3' );

结果

id2
id2#id4
id2#id4#id1
id2#id4#id1#id3