**
PLSQL程序
**
1.输出’hello 你好’字符串:
begin
dbms_output.put_line(‘hello 你好’);
end;
/
2.求10+100的和,定义变量:
declare
my number(3):=0; 变量
tip varchar2(10):=‘结果是’; 变量
begin
my:=100+10; 业务算法
dbms_output.put_line(tip||my); 输出
end;
/
3.输出7369号员工姓名和工资,定义两个变量:
declare
pename emp.ename%type;
psal emp.sal%type;
begin
select ename,sal into pename,psal from emp where empno=7369;
dbms_output.put_line(‘7369号员工姓名’||pename||‘工资’||psal);
end;
/
4.输出7788号员工姓名和工资
declare
emp_record emp%rowtype;
begin
select * into emp_record from emp where empno=7788;
dbms_output.put_line(‘7788号员工姓名’||emp_record.ename||‘工资’||emp_record.sal);
end;
/
何时使用%type,何时使用%rowtype ?
当定义变量时,该变量的类型与表中某字段的类型相同时,可使用%type;
当定义变量时,该变量与整个表结构完全相同时,可以使用%rowtype,此时通过变量名.字段名,可以取值变量中对应的值。
PLSQL判断
if语句
1.显示今天星期几,是"工作日"还是"休息日"
declare
pday varchar2(10);
begin
select to_char(sysdate,‘day’)into pday from dual;
dbms_output.put_line(‘今天是’||pday);
if pday in(‘星期六’,‘星期日’)then
dbms_output.put_line(‘休息日’);
else
dbms_output.put_line(‘工作日’);
end if;
end;
/
2.显示年龄阶段
declare
age number(3):=&age;
begin
if age<16 then
dbms_output.put_line(‘未成人’);
elsif age>=16 and age<30 then
dbms_output.put_line(‘青年人’);
elsif age>=30 and age<60 then
dbms_output.put_line(‘奋斗人’);
elsif age>=60 and age<80 then
dbms_output.put_line(‘享受人’);
else
dbms_output.put_line(‘待续…’);
end if;
end;
/
循环语句
1.显示1-10
declare
i number(2):=1;
begin
loop
exit when i>10;
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
/
2.while循环显示1-10
declare
i number(2):=1;
begin
while i<11
loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
/
3.使用for循环显示20-30
declare
i number(2):=1;
begin
for i in 20…30
loop
dbms_output.put_line(i);
end loop;
end;
/
游标
1.查询所有员工的姓名和工资
declare
cursor cemp is select ename,sal from emp;
vename emp.ename%type;
vsal emp.sal%type;
begin
open cemp;
loop
fetch cemp into vename,vsal;
exit when cemp%notfound;
dbms_output.put_line(vename||’–’||vsal);
end loop;
close cemp;
end;
/
2.查询10号部门的员工姓名和工资
declare
cursor cemp(pdeptno emp.deptno%type) is select ename,sal from emp where deptno=pdeptno;
pename emp.ename%type;
psal emp.sal%type;
begin
open cemp(&deptno);
loop
fetch cemp into pename,psal;
exit when cemp%notfound;
dbms_output.put_line(pename||‘的薪水是’||psal);
end loop;
close cemp;
end;
/