如何使用 MySQL 存储过程的游标创建逗号分隔值?

How to create a comma separated value using Cursor of MySQL Stored Procedure?

我想从游标中构造一个变量,其最终值类似于:“1,2,3”。以下是简单的存储过程:

    OPEN cursor1;
    BEGIN
        LOOP1: LOOP
        FETCH cursor1 INTO main_account_id;
        IF no_more_rows THEN
            CLOSE cursor1;
            LEAVE LOOP1;
        END IF;
        // Here I want to achieve something like "1,2,3" from main_account_id
        END LOOP LOOP1;
    END;

以下是我如何实现它的伪:

SET @comma_sep_value = "";
OPEN cursor1;
BEGIN
    LOOP1: LOOP
    FETCH cursor1 INTO main_account_id;
    IF no_more_rows THEN
        CLOSE cursor1;
        LEAVE LOOP1;
    END IF;
    SET @comma_sep_value = CONCAT(@comma_sep_value,main_account_id,","); 
    END LOOP LOOP1;
END;
SET @comma_sep_value = TRIM(BOTH ',' FROM @comma_sep_value); 
SELECT @comma_sep_value as final_val;

注意:倒数第二行是 trim 尾随逗号。

首先将您的变量定义为 NULL:

SET @comma_sep_value = NULL;

然后在循环中使用CONCAT_WS()

SET @comma_sep_value = CONCAT_WS(',', @comma_sep_value, @next_element);

没有尾随逗号,因此不需要 TRIM。