mariadb 如何通过分隔符将字符串拆分为存储函数中的结果集

问题描述 投票:0回答:1

我正在尝试创建一个可以在存储过程中调用的拆分函数,我知道有一个函数 SUBSTRING_INDEX,我试图返回临时表或 JSON 数组,但失败了。 我没有太多可展示的:

BEGIN
#Splits a subject text "strSubject" using the supplied "strPattern"
#The results are returned in the temporary table tbl_split_results
 RETURN SUBSTRING_INDEX(strSubject, strPattern, 9999);
END

调用示例:

SELECT split("Simon\r\nSusan\r\nLewis\r\nJordan\r\nOliver\r\n", "\r\n");

这仅返回带有分隔符“的单个字符串 " 已删除,我想要的是每个项目占一行。MariaDB 的版本是 11.5 (x64),在 Windows 10.0.19045.4780 上运行。

[编辑]到目前为止,但仍然有错误,也不是很有帮助的错误,代码:

CREATE DEFINER=`root`@`localhost` FUNCTION `split`(
    `ttxtSubject` TINYTEXT,
    `ttxtPattern` TINYTEXT
)
RETURNS JSON
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'splits string by pattern'
BEGIN
#Splits a subject text "ttxtSubject" using the supplied "ttxtPattern"
#The results are returned in the temporary table tbl_split_results
    DECLARE intIterator INT;
    DECLARE ttxtResult TINYTEXT;
    DECLARE jsonArray JSON;
    SET intIterator = 1;
    `forLoop`:LOOP
        #SET ttxtResult = SUBSTRING_INDEX(ttxtSubject, ttxtPattern, intIterator);
        IF NOT ttxtResult THEN LEAVE `forLoop`;
        #Json_Object_Add(jsonArray, ttxtResult);
        SET intIterator = intIterator + 1;
    END LOOP `forLoop`; 
    RETURN jsonArray;
END

我注释掉了几行来尝试调试,但没有帮助,当我尝试保存函数时显示错误:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LOOP`forLoop`;
RETURN jsonArray;
END' at line 23
mariadb
1个回答
0
投票

您的

END IF
条款中缺少
IF

你可以使用这样的东西:

create function split(
ttxtSubject tinytext,
ttxtPattern tinytext
)
returns json
comment 'splits string by pattern'
begin
-- Splits a subject text "ttxtSubject" using the supplied "ttxtPattern"
-- The result is returned as a JSON array
declare ind int default 1;
declare done int default 0;
declare item tinytext;
declare jsonArray tinytext;

while not done do
  set item = substring_index(substring_index(ttxtsubject, ttxtpattern, ind), ttxtpattern, -1);

  if (item = '') then
    set done = 1;
  else
    if (jsonArray is null) then
      set jsonArray = json_array(item);
    else
      set jsonArray = json_array_append(jsonArray, '$', item);
    end if;
  end if;

  set ind = ind + 1;
end while;

return jsonArray;
end
© www.soinside.com 2019 - 2024. All rights reserved.