首页 > 代码库 > mysql动态sql 整理多个字段
mysql动态sql 整理多个字段
原始表:
整理后的表:
方案一(动态sql):
BEGIN #Routine body goes here... DECLARE v1 int(3); DECLARE v2 int(3); #DECLARE v3 VARCHAR(15); #DECLARE vcompany VARCHAR(30); #DECLARE vname VARCHAR(30); DECLARE vcol VARCHAR(30); DECLARE tmp_sql VARCHAR(3000); DECLARE vid int(3); set v1 = 1; WHILE v1 <= 11993 DO set v2=2; #if v2 <=27 THEN WHILE v2 <=27 DO set @v3=CONCAT(‘l‘,v2); set @vcompany=‘‘; set @vname=‘‘; #set @vid=‘‘; SET @l_sql=CONCAT_ws(‘ ‘, ‘select company_name,‘,@v3, ‘into @vcompany,@vname‘, ‘from for_xun_cha where id =‘,v1); SET @sql=@l_sql; prepare stmt from @sql; execute stmt; #select company_name,l2 into vcompany,vname from for_xun_cha where id=v2; if LENGTH(trim(@vname)) > 0 THEN INSERT into tmp(company,name) VALUES(@vcompany,@vname); #INSERT into tmp(company,name) VALUES(vcompany,tmp_sql); end if; set v2 = v2+1; #end if; end WHILE; set v1 = v1 + 1; END WHILE; END
方案二(先合并各列,再用游标处理):
BEGIN DECLARE Done INT DEFAULT 0; DECLARE n int ; -- 最大列 27 DECLARE companyName VARCHAR(20) ;-- 公司名称 DECLARE personNames VARCHAR(1000);-- 员工名称 DECLARE personName VARCHAR(10); DECLARE _cur CURSOR FOR select company_name ,CONCAT_WS(",",l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13,l14,l15,l16,l17,l18,l19,l20,l21,l22,l23,l24,l25,l26,l27) from for_xun_cha; OPEN _cur; FETCH _cur INTO companyName,personNames; REPEAT IF NOT Done THEN test: WHILE(n<=27) DO set personName=SUBSTRING_INDEX(SUBSTRING_INDEX(personNames,‘,‘,n),‘,‘,-1); if ISNULL(personName) || LENGTH(trim(personName))<1 THEN LEAVE test; ELSE INSERT INTO temp1 VALUES (companyName,personName); END IF; set n=n+1; end while; end IF; set n = 1; FETCH NEXT FROM _cur INTO companyName,personNames; UNTIL Done END REPEAT; -- set personName=""; -- set personNames=""; CLOSE _cur; END
mysql动态sql 整理多个字段
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。