#创建视图 createor replace view stu_v_1 asselect id,name from student where id <=10;
#查询视图 showcreateview stu_v_1; select*from stu_v_1; select*from stu_v_1 where id<3; #修改视图 createor replace view stu_v_1 asselect id,name,num from student where id <=10; alterview stu_v_1 asselect id,name,num from student where id <=10;
createview v1 asselect id,name from student where id <=20withcascadedcheck option; createview v1 asselect id,name from student where id <=20withlocalcheck option;
cascaded 的有向上传递性,即a2基于a1创建,a1没有check option ,a2 有, 那么a1也会变得拥有这个属性 local 并没有 检查的时候都会递归检查是否有check option并服从条件
#创建视图,使用聚合函数 createview stu_v_count asselectcount(*) from student; insertinto stu_v_count vaLues(10); #报错
1 2 3 4 5 6
#1.为了保证数据库表的安全性,开发人员在操作tb_user表时,只能看到的用户的基本字段,屏蔽手机号邮箱两个字段 createview tb_user_view asselect id,name,profession,age,gender,status,createtime from tb_user; selectfrom tb_user_view;
#2.查询每个学生所选修的课程(三张表联查),这个功能在很多的业务中都有使用到,为了简化操作,定义一个视图。 createview tb-stu_course_view asselect S.name stu_name,S.no,c.name cou_name from student S,student_course sc,course c where S.id = Sc.studentid and sc.courseid = c.id;
#1 createprocedure p(in n int) begin declare total intdefault0; sum: loop if n<=0then leave sum; end if; set total := total+n; set n:=n-1; end loop sum; select total; end;
call p(90);
#2 createprocedure p2(in n int) begin declare total intdefault0; sum:loop if n<=0then leave sum; end if; if n%2==1then set n := n-1; iterate sum; end if; set total := total + n; set n := n-1; end loop sum; select total; end;
createprocedure p(in uage int) begin declare uname varchar(100); declare upro varchar(100); declare u_cursor cursorforselect name,profession from tb_user where age <= uage; declare exit handler forsqlstate'02000'close u_cursor; #declare exit handler fornot found close u_cursor; droptable if exists tb_user_pro; createtable if notexists tb_user_pro( id intprimary key auto_increment, name varchar(100), profession varchar(100) ); open u_cursor; while true do fetch u_cursor into uname,upro; insertinto tb_user_pro values(null,uname,upro); end while; close u_cursor; end;
2.5 存储函数
存储函数在实际中应用不广泛,可以被存储过程代替 其参数只能时in类型
1 2 3 4 5 6 7 8 9 10 11
createfunction 存储函数名称([参数列表]) return type [characteristic...] begin SQL return ...; end;
characteristic说明: deterministic :相同的输入参数总是产生相同的结果 nosql : 不包含SQL语句 readssql data : 包含读取数据的语句,但不包含写入数据的语句
eg
1 2 3 4 5 6 7 8 9 10 11 12
createfunction fun(n int) returnintdeterministic begin declare total intdefault0; while n>0 do set total := total + n; set n := n-1; end while; return total; end;