如何在MySql中合并值?

时间:2018-07-05 07:13:00

标签: mysql sql

请找到以下代码,以下代码是sql服务器代码[存储过程]我正在此链接mysql中将sql转换为mysql,下面是sql SP

USE databasename
GO
ALTER PROCEDURE GetSbsberIDbyDept
    @P_DepartmentIds varchar(max),
    @OP_ID varchar(max) output
AS
BEGIN
     Declare @Position int
     Declare @length int
     Declare @value varchar(8000)
     Declare @SubscribrIDs varchar(max)
     Declare @FinalSubscriberids varchar(max) = ''
     SET @Position = 0
     SET @length = 0
     select @P_DepartmentIds
         WHILE CHARINDEX(',', @P_DepartmentIds, @Position+1)>0
           BEGIN
             set @Length = CHARINDEX(',', @P_DepartmentIds, @Position+1) - @Position
             set @value = SUBSTRING(@P_DepartmentIds, @Position, @length)
             select @SubscribrIDs = STUFF((SELECT ', ' + cast(SubscriberId as varchar(max)) from SbsberDetails  
             where Deptid =  @value and ParentId is null order by SubscriberId asc FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
             if(@SubscribrIDs is not null)
              begin
                set @FinalSubscriberids += cast(@SubscribrIDs as varchar(max)) + ',';
              end
              set @Position = CHARINDEX(',', @P_DepartmentIds, @Position + @length) +1
           END
           SET @OP_ID =  @FinalSubscriberids
END

然后我转换为MySql,但是我在STUFF语句中遇到错误,例如 STUFF在此位置无效输入,下面是Mysql代码

    USE databasename     
DELIMITER //

CREATE PROCEDURE GetSbsberIDbyDept(
    p_P_DepartmentIds longtext,
    p_OP_ID out longtext )
BEGIN
     Declare v_Position int;
     Declare v_length int;
     Declare v_value varchar(8000);
     Declare v_SubscribrIDs longtext;
     Declare v_FinalSubscriberids longtext Default '';
     SET v_Position = 0;
     SET v_length = 0;
     select p_P_DepartmentIds
         WHILE; CHARINDEX(',', p_P_DepartmentIds, v_Position+1)>0
           BEGIN
             set v_length = CHARINDEX(',', p_P_DepartmentIds, v_Position+1) - v_Position;
             set v_value = SUBSTRING(p_P_DepartmentIds, v_Position, v_length);
             set v_SubscribrIDs = STUFF((SELECT Concat(', ' , cast(SubscriberId as longtext)) from SbsberDetails  
             where Deptid =  v_value and ParentId is null order by SubscriberId asc FOR XML; PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
             if(v_SubscribrIDs is not null)
              then
                set v_FinalSubscriberids += concat(cast(v_SubscribrIDs as longtext) , ',');
              end if;
              set v_Position = CHARINDEX(',', p_P_DepartmentIds, v_Position + v_length) +1;
           END;
           SET p_OP_ID =  v_FinalSubscriberids;            
END;
//

DELIMITER ;

如何将上述sql代码转换为MySql?

1 个答案:

答案 0 :(得分:0)

STUFF是SQL Server函数,因此在mysql中引发错误,我得到的东西试图行连接,但是在mysql中,有用于组初始化的函数名GROUP_CONCAT,因此您可以使用它代替东西