如何将此MSSQL游标函数转换为MYSQL

时间:2017-03-01 18:28:12

标签: mysql sql-server function cursor

我正在尝试将MSSQL函数转换为MySQL。这是我到目前为止所做的。有人可以看一下吗?

ALTER FUNCTION [dbo].[GetCommaDelimitedCategoryIDs]
(
    @datafeedcategoryinfoid int
)
RETURNS varchar(2000)
AS
BEGIN

DECLARE @category_list varchar(4500), @categoryid varchar(20)
SET @category_list = ''

  DECLARE category_cursor CURSOR 
  LOCAL FAST_FORWARD FOR 
  SELECT DISTINCT categoryid
  FROM category_mapping
    WHERE datafeedcategoryinfoid = @datafeedcategoryinfoid

  OPEN category_cursor;

  FETCH NEXT FROM category_cursor
  INTO @categoryid;

  WHILE @@FETCH_STATUS = 0
  BEGIN

    SET @category_list = @category_list + @categoryid + ','

    FETCH NEXT FROM category_cursor
    INTO @categoryid;

  END

  CLOSE category_cursor;
  DEALLOCATE category_cursor;

  IF (LEN(@category_list) > 0)
    SET @category_list = SUBSTRING(@category_list, 1, LEN(@category_list) - 1)

  RETURN @category_list


END

这是MySQL函数

DELIMITER $$

CREATE DEFINER=``@`` FUNCTION `GetCommaDelimitedCategoryIDs`(
    p_datafeedcategoryinfoid int
) RETURNS varchar(2000) CHARSET latin1
BEGIN

DECLARE v_category_list varchar(4500);
DECLARE v_categoryid varchar(20);
DECLARE category_cursor CURSOR FOR 
    SELECT DISTINCT categoryid 
    FROM category_mapping 
    WHERE datafeedcategoryinfoid = p_datafeedcategoryinfoid;

    SET v_category_list = '';
    OPEN category_cursor;

    myloop: LOOP
    FETCH category_cursor INTO v_categoryid;
    IF done THEN
        LEAVE myloop;
    END IF;
    SET v_category_list = Concat(v_category_list , v_categoryid , ',');
    FETCH category_cursor INTO v_categoryid;

    END LOOP;

  CLOSE category_cursor;


  IF (CHAR_LENGTH(RTRIM(v_category_list)) > 0) THEN
    SET v_category_list = SUBSTRING(v_category_list, 1, CHAR_LENGTH(RTRIM(v_category_list)) - 1);
  END IF;

  RETURN v_category_list;


END

但是上面的函数没有返回值。 Mysql Workbench不会返回任何错误,我该怎么调试?

1 个答案:

答案 0 :(得分:2)

这不是group_concat()的工作吗?类似的东西:

select group_concat(distinct categoryid order by categoryid SEPARATOR ',')
from category_mapping 
where datafeedcategoryinfoid = p_datafeedcategoryinfoid;

这是demo of group_concat()