学习资料来源于:【Oracle】黑马57期Oracle数据库基础教程_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili
先来学习声明方法,declare-begin-end;
【代码展示】:
--声明方法
--赋值方法可以用:=也可以用into查询语句赋值
declare
i number(2):=10;
s varchar2(10):='小明';
ena emp.ename%type;--引用型变量,将ename列的类型赋值给ena
emprow emp%rowtype;--记录型变量,存放的是一行记录
begin
dbms_output.put_line(i);
dbms_output.put_line(s);
select ename into ena from emp where empno=7788;--一个into即可赋值
dbms_output.put_line(ena);
select * into emprow from emp where empno=7788;
dbms_output.put_line(emprow.ename || '的工作为:'|| emprow.job);
end;
代码最后一行一开始写的是dbms_output.put_line(emprow);
出现了错误,显示put_line参数个数或类型错误,这才知,
emprow没有明确的指向性,当限定empno=7788时,ena已明确了结果,而emprow是一行记录。
第二个学习一下if判断,
涉及语法为:if then-elsif then-elsif then-else-end if
【代码展示】:
--pl/sql中的if判断
--输入小于18的数字,输出未成年
--输入大于18小于40的数字,输出中年人
--输入大于40的数字,输出老年人
declare
i number(3):=ⅈ
begin
if i<18 then
dbms_output.put_line('未成年');
elsif i<40 then
dbms_output.put_line('中年人');
else
dbms_output.put_line('老年人');
end if;
end;
第三个学习一下循环语句,
涉及语法为:while loop-end loop、loop-exit when-end loop、for loop-end loop
【代码展示】:
--pl/sql中的loop循环
--用三种方法输出1-10个数字
--while循环
declare
i number(2):=1;
begin
while i<11 loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
--exit循环(用的最多的)
declare
i number(2):=1;
begin
loop
exit when i>10;
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
--for循环(最容易的)
declare
begin
for i in 1..10 loop
dbms_output.put_line(i);
end loop;
end;
值得注意的是,在使用循环时,要考虑好dbms_output.put_line(i)的摆放位置,
如在exit when中,本人写的是
dbms_output.put_line(i);
exit when i>10;
i:=i+1;
end loop;
那么得到的结果为:1 2 3 4 5 6 7 8 9 10 11,不符合要求,
改为:
exit when i>10;
dbms_output.put_line(i);
i:=i+1;
end loop;
那么得到的结果为:1 2 3 4 5 6 7 8 9 10,符合要求。
第四个学习游标,那么什么是游标?
它可以存放多个对象,多行记录。
【代码展示】:
--输出emp表中所有员工的姓名
declare
cursor c1 is select * from emp;--将emp表中全部记录存进游标中
emprow emp%rowtype;
begin
open c1;
loop
fetch c1 into emprow;
exit when c1%notfound;
dbms_output.put_line(emprow.ename);
end loop;
close c1;
end;
--给指定部门的员工涨工资
declare
cursor c2(eno emp.deptno%type)
is select empno from emp where deptno=eno;
en emp.empno%type;
begin
open c2(10);
loop
fetch c2 into en;
exit when c2%notfound;
update emp set sal=sal+10 where empno=en;
commit;
end loop;
close c2;
end;
--查询10号部门的员工信息
select * from emp where deptno=10;