2017-03-01 67 views
0

我試圖將MSSQL函數轉換爲MySQL。這是我迄今爲止所做的。有人可以看看嗎?如何將此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

這不是'group_concat()'的工作嗎? – SqlZim

回答

2

這不是group_concat()的工作嗎?例如:

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

這是demo of group_concat()

+0

對不起,你能更具體嗎?我應該把你的上述選擇語句替換掉嗎? – Sravsk

+0

@sravsk你根本不需要自定義函數,你可以使用mysql內置的'group_concat()' – SqlZim

+0

上面的解決方案工作。感謝您的選擇。 – Sravsk