PLSQL编程: procedure Language 过程语言 oracle对sql的一个扩展
让我们能够像在java中一样写 if else else if 条件,还可以编写循环逻辑 for while
declare
--声明变量
变量名 变量类型 ;
变量名 变量类型 :=初始值;
begin
--业务逻辑
end;
dbms_output.put_line() 相当于java中的system.out
例1:声明一个字符串类型变量赋值为张三并输出打印。
declare
name varchar2 (10) :='张三';
begin
dbms_output.put_line(name);
end ;
例2:查询员工编号为7369的工资,并打印出来
declare
salary emp.sal%type ; --声明一个引用类型的变量,变量类型代表和emp表中的变量类型相同。
begin
--将查询出的结果值赋值给声明的变量
select sal into salary from emp where empno = '7369';
dbms_output.put_line(salary);--打印变量值
end;
例3:声明一个记录型的变量 语法 vrow emp%rowtype
declare
vrow emp%rowtype;
begin
--查询编号为7369的一条记录信息并赋值给声明的变量
select * into vrow from emp where empno ='7369'
--打印输出
dbms_output.put_line('姓名:'|| vrow.name || '工资:' || vrow.sal);
end;
-------PLSQL中的条件判断
if then
elseif then
else
end if;
例5:根据不同年纪输出相关内容
declare
age number :=20;--声明一个number类型的变量age赋值为20
--如果 写成 age number :=&aaa 则表示age是个可变的变量,执行sql时可在弹窗中自由录入aaa的值。
begin
if age<18 then
dbms_output.put_line('未成年');
elseif age>=18 and age <=24 then
dbms_output.put_line('年轻人');
elseif age>24 and age >40 then
dbms_output.put_line('老司机');
else
dbms_output.put_line('老nian ren ');
end if;
end;
---循环操作
while循环语法
while 条件 loop
end loop;
for循环语法
for 变量 in 【reverse --加上此=关键字表示倒序】 起始值..结束值 loop
end loop;
loop循环
loop
exit when 条件
end loop;
例6:输出1到10
declare
i number :=1;
begin
while i<=10 loop
dbms_output.put_line(i);
i :=i+1;
end loop;
end;
for循环案例
declare
--注意for循环时无需在这里定义变量
begin
for i reveser 1..10 loop --倒序输出10-1
dbms_output.put_line(i);
end loop;
end;
loop循环:
declare
i number :=1;
begin
loop
exit when i>10 ;
i :=i+1;
dbms_output.put_line(i);
end loop;
end;