MySQL函数从String返回多个Int

时间:2013-01-25 18:04:50

标签: java mysql function stored-procedures

我希望将来自Java方法的字符串“1,3,5,7,9,0,3”传入函数,并将函数返回由逗号分隔的每个值作为然后将在存储过程中使用Int(如下所示)。

CREATE PROCEDURE updateLastModifiedDate(IN p_classId VARCHAR(21844), IN p_timestamp VARCHAR(21844))
    BEGIN
        SET @query = CONCAT ('UPDATE class SET LastModifiedDate = ',p_timestamp,' WHERE ClassId IN (', p_classId ,')');
        PREPARE stmt FROM @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END //
DELIMITER ;

我该怎么写这个函数?

1 个答案:

答案 0 :(得分:1)

在您的情况下,函数的输入是COMMA SEPARATED字符串。但MySql不包含用于拆分COMMA SEPARATED字符串的内置函数(逗号只是分隔符的示例)。

您已将输入提及为“1,3,5,7,9,0,3”。这意味着,项目数为7.此计数需要为常数。我可以举个例子,但是项目的数量应该是常数。

此外,mysql函数只能返回单个值。因此,您必须仅在函数内调用过程(在拆分值之后)。

我给你一个mysql function假设输入字符串包含7个项始终并且使用的分隔符是逗号。否则你必须修改这个功能。

DELIMITER @@

CREATE FUNCTION getCustomerFullName(commaSeparatedString VARCHAR(256))
RETURNS INT
BEGIN
  DECLARE value1 INT DEFAULT 0;
  DECLARE value2 INT DEFAULT 0;
  DECLARE value3 INT DEFAULT 0;
  DECLARE value4 INT DEFAULT 0;
  DECLARE value5 INT DEFAULT 0;
  DECLARE value6 INT DEFAULT 0;
  DECLARE value7 INT DEFAULT 0;

  IF NOT commaSeparatedString IS NULL
    THEN
          SELECT LENGTH(commaSeparatedString) - LENGTH(REPLACE(commaSeparatedString, ',', '')) INTO @commaCount;

          IF  @commaCount = 0
            THEN
                 RETURN 0;  
          ELSE
            SET value1 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 1),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 0)) + 1), ',', '');
            SET value2 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 2),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 1)) + 1), ',', '');
            SET value3 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 3),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 2)) + 1), ',', '');
            SET value4 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 4),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 3)) + 1), ',', '');
            SET value5 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 5),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 4)) + 1), ',', '');
            SET value6 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 6),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 5)) + 1), ',', '');
            SET value7 = REPLACE(SUBSTRING(SUBSTRING_INDEX(commaSeparatedString, ',', 7),LENGTH(SUBSTRING_INDEX(commaSeparatedString, ',', 6)) + 1), ',', '');

        END IF;
  END IF; 

  CALL updateLastModifiedDate(value1, value2, value3, value4, value5, value6, value7);

  RETURN 1;
END;
@@

DELIMITER ;

提供者: