Simple use of PL/SQL and summary of small details

Basic usage

basic framework

declare
//声明变量部分
//格式:变量名:变量类型 [赋初值:=value];
//两个比较特殊的变量类型(记录类型)%type:该变量与表中某数据类型相同;%rowtype:该变量与表的数据类型相同。
//例如:v_ename emp.ename%type;  rec_emp emp%rowtype;%rowtype可以理解为对象或者结构体
begin
//运算部分
//可以单纯地当作一个编程语言,也可以结合sql语句实现功能,后面会有举例
exception
//处理异常
end;//结束标志
/ //执行

declare variable and output


declare
  v_no varchar(12) := '123';
  v_name varchar(6) := 'zwq';
begin
  dbms_output.put_line('学号:'||v_no||',姓名:'||v_name);
end;
/

Output the department name and number of employees of department No. 30 (%type)


declare
  v_dname dept.dname%type;
  v_count int;
begin
  select dname into v_dname from dept where deptno = 30;
  //into 可以看做将前面查出来的数据dname放入v_dname变量中
  select count(*) into v_count from emp where deptno = 30;
  dbms_output.put_line('部门名称:'||v_dname||',员工数:'||v_count);
end;
/

Output the first item of the emp table to record the employee's job ID, manager ID and job type (%rowtype)


declare
  emp_type emp%rowtype;
begin
  select * into emp_type from emp where rownum = 1;
  //把查询出来的数据全部放入emp_type中
  dbms_output.put_line('工号:'||emp_type.empno||',经理号:'||emp_type.mgr||',工种:'||emp_type.job);
  //用 . 调用数据
end;
/

Frequently Asked Questions

Execute the output statement without reporting an error but no output

Solution: Turn on the output package service

set serveroutput on;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325965531&siteId=291194637