mysql动态sql 整理多个字段
Posted vijayfly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 整理多个字段的主要内容,如果未能解决你的问题,请参考以下文章