一、sql的dml
1)、查询,运用 select into
实例(只能查询的单个数据:有且只有一个值 “不能有多个值,不能为空”):
/**
操作 select ,使用 select into
*/
declare
v_ename emp.ename%type;
begin
--获取 工资为 800的员工姓名
select ename into v_ename from emp where sal=800;
dbms_output.put_line(v_ename);
end;
除此之外,还可以添加异常处理
例如:
--加入异常
declare
v_ename emp.ename%type;
begin
--获取 工资为 800的员工姓名
select ename into v_ename from emp where sal=&月薪;
dbms_output.put_line(v_ename);
exception
when no_data_found then
dbms_output.put_line('数据未找到'||sqlcode||'-->'||sqlerrm);
when too_many_rows then
dbms_output.put_line('数据超出'||sqlcode||'-->'||sqlerrm);
when others then
dbms_output.put_line('其他异常'||sqlcode||'-->'||sqlerrm);
end;
二、异常
异常 exception: 非正常情况
1、no_data_found :数据未找到
2、to_many_rows :数据太多
3、others
三、控制语句
1.选择语句
1)格式如下
if then
elsif then
…
else
end if;
2)实例:--计算年薪
declare
--获取员工的 奖金
v_income emp.sal%type;
begin
execute immediate 'select (nvl(comm,0)+sal)*12 from emp where empno=&员工编号 ' into v_income;
--判断
if v_income<10000 then
dbms_output.put_line('1');
elsif v_income<50000 then
dbms_output.put_line('2');
else
dbms_output.put_line('不错');
end if;
exception
when no_data_found then
dbms_output.put_line('数据未找到'||sqlcode||'-->'||sqlerrm);
when too_many_rows then
dbms_output.put_line('数据超出'||sqlcode||'-->'||sqlerrm);
when others then
dbms_output.put_line('其他异常'||sqlcode||'-->'||sqlerrm);
end;
2、循环
循环四要素: 初始表达式 条件表达式 迭代因子 循环体
1)、直到型(先执行后判断)
格式为:
loop
exit when 条件
end loop;
实例:
--直到型
declare
--100以内的奇数
--1、初始化表达式
v_num number(5):=1;
begin
loop
--2、循坏体
if mod(v_num,2)=1 then
dbms_output.put_line(v_num);
end if;
exit when v_num>=100; --3、条件
--4、迭代因子
v_num :=v_num+1;
end loop;
end;
2)、当到型
格式为:while 条件 loop
end loop;
实例:
--当到型
declare
--100以内的奇数
--1、初始化表达式
v_num number(5):=1;
begin
--3、条件
while v_num<=100 loop
--2、循坏体
if mod(v_num,2)=1 then
dbms_output.put_line(v_num);
end if;
--4、迭代因子
v_num :=v_num+1;
end loop;
end;
3)、for
变量不需要声明 变量,变量的值不能改变,内部值+1
格式:
for index in [reverse] min..max loop
end loop
declare
--1..100的奇数
--初始化表达式
v_num number(5):=1;
begin
for i in 1..100 loop
if mod(i,2)=1 then
dbms_output.put_line(i);
end if;
end loop;
end;
for的内部倒叙操作 reverse
实例
--for (倒转输出)
declare
--1..100的数
--1、初始化表达式
v_num number(5):=1;
begin
for i in reverse 1..100 loop
dbms_output.put_line(i);
end loop;
end;