在Mysql函数中如何返回多行

时间:2012-11-06 11:18:56

标签: mysql sql

我正在使用MySQL。我可以在MySQL程序中获得更多行但不在函数中。我想通过返回多行的值来编写函数。我附上我的部分代码:

drop function if exists test_splitfn;
DELIMITER $$

CREATE Function test_splitfn( sSepar VARCHAR(255), saVal TEXT )
Returns @MyTable table 
body:

BEGIN

  DROP TEMPORARY TABLE IF EXISTS lib_Explode;
  CREATE TEMPORARY TABLE lib_Explode(
    pos int unsigned NOT NULL auto_increment,
    val VARCHAR(255) NOT NULL,
    PRIMARY KEY  (pos)
  ) ENGINE=Memory COMMENT='Explode() results.';

  IF sSepar IS NULL OR saVal IS NULL THEN LEAVE body; END IF;

  SET @saTail = saVal;
  SET @iSeparLen = LENGTH( sSepar );

  create_layers:
  WHILE @saTail != '' DO

    # Get the next value
    SET @sHead = SUBSTRING_INDEX(@saTail, sSepar, 1);
    SET @saTail = SUBSTRING( @saTail, LENGTH(@sHead) + 1 + @iSeparLen );
    INSERT INTO lib_Explode SET val = @sHead;

  END WHILE;

     Insert @MyTable
      SELECT val  FROM lib_Explode;


    return @MyTable;
END; $$
DELIMITER ;

2 个答案:

答案 0 :(得分:3)

在MySQL函数中,你无法返回表..

答案 1 :(得分:0)

尝试这样的事情:

DROP FUNCTION IF EXISTS test_splitfn;
DELIMITER $$

CREATE PROCEDURE test_splitfn (IN sSepar VARCHAR(255), saVal TEXT)
body:BEGIN

    DROP TEMPORARY TABLE IF EXISTS lib_Explode;
    CREATE TEMPORARY TABLE lib_Explode(
        pos int unsigned NOT NULL auto_increment,
        val VARCHAR(255) NOT NULL,
        PRIMARY KEY  (pos)
    ) ENGINE=Memory COMMENT='Explode() results.';

    IF sSepar IS NULL OR saVal IS NULL THEN
        LEAVE body;
    END IF;

    SET @saTail = saVal;
    SET @iSeparLen = LENGTH( sSepar );

    WHILE (@saTail != '') DO
        SET @sHead = SUBSTRING_INDEX(@saTail, sSepar, 1);
        SET @saTail = SUBSTRING( @saTail, LENGTH(@sHead) + 1 + @iSeparLen );
        INSERT INTO lib_Explode SET val = @sHead;
    END WHILE;

    SELECT val FROM lib_Explode;
END$$
DELIMITER ;