PL/SQL语句块提高1+case语句

时间:2021-07-03 20:36:02
set serveroutput on;
declare
--默认值的bianliang
v_a number:=0;
--
v_b integer;
--用stud.id 的类型
v_id stud.id%type;
--
nm stud.name%type;
begin
nm:='jack';
v_id:=89;
DBMS_OUTPUT.PUT_LINE('你的名字是:'||nm||'你的id'||v_id);
end;
---调用splql需要权限
grant debug connect session to 用户名;
grant debug any procedure to 用户名;
-------------------
--------接受用户输入-----------
accept abc prompt '输入年龄';
declare
age integer;
begin
--用取地址获取abc中的值
age:=&abc;
DBMS_OUTPUT.PUT_LINE('age is :'||age);
end; --查询stud表中有多少行记录count
declare
v_count integer;
v_avg numeric(10,2);
begin
--将查询结果设置给变量
select count(1),avg(id) into v_count,v_avg from stud;
DBMS_OUTPUT.PUT_LINE('人数'||v_count||'avg is :'||v_avg);
end;
select * from stud;
---------------------------------------------------------
-----------------------case语句----------------------------------
--------------------------------------------------------
--case when then语句,只能设置值
drop table stud1;
create table stud1(
id int,
name varchar(30),
age int,
sex char(1)check (sex in('1','0'))
);
insert into stud1 values(7,'k7',20,2);
insert into stud1 values(2,'k2',22,0);
insert into stud1 values(3,'k3',24,1);
--第一种方法
select * from stud1;
select id,name,age,(case sex when '1'then '男'else '女'end)
as sex from stud1;
--第二方法
select id,name,age,(case when sex='1'then '男' else '女'end)
as sex from stud1;
--多个when
select id,name,age,(case when sex='1' then '男的'when sex='2'then '不知道'
else'女的'end)as sex from stud1;
--利用plsql块中使用查询是男还是女
---------------------------------------------------
declare
v_result varchar(30);
v_id integer;
begin
v_id:=&id;
--先查询
select sex into v_result from stud1 where id=v_id;
v_result :=
case v_result
when '1' then '男'
when '0' then '女'
else '不知道'
end;
DBMS_OUTPUT.PUT_LINE('编号为'||v_id||'的是:'||v_result);
end;