为什么以下循环不在其他 staffid 上循环?

Why the following loop is not looping on other staffid?

我想为拥有多个员工的分支机构生成月度报告

我有这个 staffid '275,222,278',但结果只显示 staffid 275,似乎 set @staff = @staff+1 不工作。

但是,如果我将此行更改为 set @staffid := (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@staffID, ',', @staff),',',-1)) ,我将 @staff 硬编码为 2,将显示员工 222 的数据,如果硬编码为 3,将显示员工 278 的数据

下面是存储过程中的循环函数

set @staffID := '275,222,278';
set @countstaff := (LENGTH(@staffID) - LENGTH(REPLACE(@staffID, ',', '')) + 1);
set @staff := 1;

WHILE @staff <= @countstaff
DO
    set @staffid := (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@staffID, ',', @staff),',',-1));
    set @loanID := (select GROUP_CONCAT(id) from sharing_profit where sharing_profit=@staffid);
    
    set @dataArr =  (SELECT JSON_ARRAYAGG(x) FROM
        (SELECT JSON_OBJECT(
            @staffid,get_revenuestamprepayment31(@staffid,YEAR_,MONTH_,@loanID)
        ) as x) AS tbl);
                    
    set @totalrows = (select JSON_LENGTH(@dataArr));
    if @totalrows is null then 
        set @err := 'RecordNotFound';
        LEAVE MyScope;
    end if;
        
    set @staff = @staff+1;
    
END WHILE;

结果是这样的,没有显示其他staffid

    "275": [
      {
        "07": [
          {
            "stamp": {
              "tepi": null,
              "account": null
            },
            "revenue": {
              "tepi": null,
              "account": 5445
            },
            "fullname": "ss2",
            "staff_id": 275,
            "staff_code": "3143414342ss2"
          }

上面的循环有什么问题?

问题是您在此处重新定义 @staffid 变量:

    set @staffid := (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@staffID, ',', @staff),',',-1));

所以下一次循环,它无法从列表中获取下一个 ID,因为现在 @staffid 只包含第一个 ID。

使用不同的变量@cur_staffid