1、输出菱形
declare
m number := 3;
begin
for y in -m..m loop
for x in -m..m loop
if abs(y) + abs(x) <= m then
dbms_output.put('*');
else
dbms_output.put(' ');
end if;
end loop;
dbms_output.new_line();
end loop;
end;
运行结果
2、编写一个程序,用于接受用户输入的数字,将该数左右反转,然后显示反转后的数。
declare
score number(10);
tp number;
rem number(10):=0;
begin
score:=&请输入要反转的数字;
while score > 0 loop
tp := mod(score,10);
rem := (rem*10)+tp;
score := trunc(score/10);
end loop;
dbms_output.put_line('反转后的数字为:'|| rem);
end;
运行结果
3、编写一个程序,往一个表中查询数据,如果没有查到任何数据,将引发no_data_found异常,显式一则消息。
declare
empname varchar2(20);
begin
select ename into empname from emp where sal>8000;
dbms_output.put_line(empname);
exception
when no_data_found then dbms_output.put_line('未找到任何数据');
when too_many_rows then dbms_output.put_line('查询结果返回多行');
end;
这里以oracle的自带emp表为例
运行结果
4、编写一个程序,接受用户输入的一个值,然后根据该值从一个表中检索出数据,如果这时检索出的记录多于一条,就引发TOO_MANY_ROWS异常,显式消息“返回多行”。
declare
empname varchar2(20);
num number;
begin
num:= &请输入你要查询的工资数目;
select ename into empname from emp where sal>num;
dbms_output.put_line(empname);
exception
when no_data_found then dbms_output.put_line('未找到任何数据');
when too_many_rows then dbms_output.put_line('返回多行');
end;
运行截图
返回多行
未找到任何数据
5、编写一个程序,接受特定玩具的ID,比较玩具的价格并显示折扣,如果价格高于或等于500元,则优惠150元;价格高于或等于400元,则优惠100元;如果价格高于或等于250元,优惠50元,价格低于250元,则不优惠。
declare
price number;
num number;
begin
price:= &请输入玩具的价格;
if price >= 500 then
num := price - 150;
dbms_output.put_line('优惠金额150元,应付款'||num||'元');
elsif price >= 400 then
num := price - 100;
dbms_output.put_line('优惠金额100元,应付款'||num||'元');
elsif price >= 250 then
num := price - 50;
dbms_output.put_line('优惠金额50元,应付款'||num||'元');
else
dbms_output.put_line('应付款'||price||'元');
end if;
end;
运行截图
6、编写一个程序,接受用户输入部门编号、部门名称、部门地址,将其插入到scott.dept表中。
declare
dept_no dept.deptno%type;
dept_name dept.dname%type;
dept_loc dept.loc%type;
begin
dept_no:=&部门编号;
dept_name:='&部门名称';
dept_loc:='&部门地址';
--insert into dept values(dept_no,dept_name,dept_loc);
--commit;
execute immediate 'insert into dept values(:1,:2,:3)'
using dept_no,dept_name,dept_loc;
commit;
end;
运行截图