已知表:t_score
id subject score
1 JAVA 60
2 MYSQL 80
3 LINUX 55
4 PYTHON 50
5 HTML 70
编写一条sql,增加是否及格列,显式如下(及格分数为60):
id subject score mark
1 JAVA 60 ok
2 MYSQL 80 ok
3 LINUX 55 no
4 PYTHON 50 no
5 HTML 70 ok
建表代码如下
# 2.题目已知表:t_score
drop table if exists t_score;
create table if not exists t_score(
id int comment '学号',
`subject` varchar(10) comment '科目',
score int comment '成绩'
)engine = innodb default charset = utf8 comment '成绩表';
# 插入数据
insert into t_score values (1,'JAVA',60),(2,'MYSQL',80),(3,'LINUX',55),(4,'PYTHON',50),(5,'HTML',70);
# 查看表数据
select * from t_score;
ALTER TABLE t_score ADD mark varchar(10);
update t_score set mark='ok' where score>=60;
update t_score set mark='no' where score<60;
用存储过程:
delimiter &&
CREATE PROCEDURE test()
begin
declare sid int;
declare sscore int;
DECLARE not_finished boolean;
DECLARE t_score_cursor cursor FOR select id,score from t_score;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_finished=false;
set not_finished = true;
open t_score_cursor;
alter table t_score add mark varchar(3);
while not_finished do
fetch t_score_cursor into sid,sscore;
update t_score set mark =
case when sscore>=60 then 'ok'
when sscore <60 then 'no'
else ''
end
where id = sid;
end while;
close t_score_cursor;
end &&
delimiter ;
调用:
call test();