交叉表查询中文,问题已解决,但是在查询出来的结果却多了一列。帮忙看看哪错了
下边是我写的存储过程:
create procedure test1()
begin
DECLARE done int default 0;
DECLARE asubject CHAR(20) character set gbk;
DECLARE str VARCHAR(1000) default '';
DECLARE cur1 CURSOR FOR select DISTINCT subject from test ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
open cur1;
REPEAT
if not done then
FETCH cur1 INTO asubject;
set str=CONCAT(str, ',', 'SUM(if(subject=''', asubject, ''', sources, 0))', '''', asubject,'''');
end IF;
UNTIL done END REPEAT;
set @sqlString=CONCAT(' select number as 学号',str, ' from test group by number ');
prepare sqlstmt from @sqlString;
execute sqlstmt;
deallocate prepare sqlstmt;
end
结果:
学号 语文 数学 英语 英语1
160707575
255537575
380000
40000
5009191
表里面是没有英语1这一科目的,但是查询出来的却多而来这一列
[解决办法]
打印出来这个变量看看就知道了
[解决办法]
set @sqlString=CONCAT(' select number as 学号',str, ' from test group by number ');
这句下面
select @sqlString;
[解决办法]
create procedure test1()
begin
DECLARE done int default 0;
DECLARE asubject CHAR(20) character set gbk;
DECLARE str VARCHAR(1000) default '';
DECLARE cur1 CURSOR FOR select DISTINCT subject from test ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
open cur1;
REPEAT
FETCH cur1 INTO asubject;
if not done then
set str=CONCAT(str, ',', 'SUM(if(subject=''', asubject, ''', sources, 0))', '''', asubject,'''');
end IF;
UNTIL done END REPEAT;
set @sqlString=CONCAT(' select number as 学号',str, ' from test group by number ');
prepare sqlstmt from @sqlString;
execute sqlstmt;
deallocate prepare sqlstmt;
end