是否可以创建这个mysql函数?

时间:2015-05-08 22:43:32

标签: mysql sql function

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

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

调用此函数就像这样

myFunction('value2#value1#value4')

并且必须返回

'id2#id1#id4'

非常感谢

3 个答案:

答案 0 :(得分:2)

你可以使用类似的东西,

CREATE FUNCTION myFunction (param1) RETURNS datatype
[NOT] DETERMINISTIC 
statements

查看此链接以获取更多信息 http://www.mysqltutorial.org/mysql-stored-function/

答案 1 :(得分:2)

你有什么理由不能运行这种查询吗?

SELECT GROUP_CONCAT(id ORDER BY FIELD(`value`, 'value2', 'value1', 'value4'))
FROM myTable
WHERE `value` IN ('value2','value1','value4')
;

编辑:添加value作为FIELD()函数的第一个参数,使其以正确的顺序返回id。

答案 2 :(得分:2)

这是一个如何做到这一点的演示,当然你可以把所有这些放在一起,但我发现分割功能更清晰。

检查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