ORACLE PL/SQL语法总结

时间:2022-07-05 22:57:14


--定义数组类型

DECLARE 
  type array_var is table of t_t_student.name%type index by binary_integer;
  v_name array_var;
begin
  v_name(-1) := '张伯伦';
  dbms_output.put_line(v_name(-1));
end;
--record类型两种定义方式
declare
 type record_var is record(
      re_num t_t_student.id%type,
      re_name t_t_student.name%type,
      re_age t_t_student.age%type
  );
  v_record record_var;
begin
  v_record.re_num := 1;
  v_record.re_name := '张宗昌';
  v_record.re_age := 32;
  dbms_output.put_line('编号:'||v_record.re_num||', 姓名:'||v_record.re_name||', 年龄'||v_record.re_age);
end;


declare
  v_record t_t_student%rowtype;
begin
  v_record.id := 1;
  v_record.name := '张宗昌';
  v_record.age := 32;
  v_record.phone := '13823475647';
  v_record.address := '大同';
  dbms_output.put_line('编号:'||v_record.id||', 姓名:'||v_record.name||', 年龄'||v_record.age||',电话:'
  ||v_record.phone||',地址:'||v_record.address);
end;
--查询
declare 
  v_record t_t_student%rowtype;
begin
  select * into v_record from t_t_student where id = 20;
  dbms_output.put_line('编号:'||v_record.id||', 姓名:'||v_record.name||', 年龄'||v_record.age||',电话:'
  ||v_record.phone||',地址:'||v_record.address);
end;
--添加
declare 
  v_record t_t_student%rowtype;
begin
  v_record.id := 24;
  v_record.name := '触子';
  v_record.age := 44;
  v_record.phone := '13950152065';
  v_record.address := '临淄';
  insert into t_t_student values(v_record.id,v_record.name,v_record.age,v_record.phone,v_record.address);
  commit;
  dbms_output.put_line('编号:'||v_record.id||', 姓名:'||v_record.name||', 年龄'||v_record.age||',电话:'
  ||v_record.phone||',地址:'||v_record.address);
end;
--删除
begin
  delete  from t_t_student where id = 21;
  dbms_output.put_line(sql%rowcount||'条记录被影响');
  commit;
end;
--修改
declare 
  v_record number(3) :=20;
begin
  update t_t_student set name='犀首' where id =v_record;
  dbms_output.put_line(sql%rowcount||'条记录被影响');
  commit;
end;
--条件语句
declare
  v_name varchar2(21) := '犀首';
BEGIN
  if(v_name = '犀首' )then
    dbms_output.put_line('正确');
  else 
    dbms_output.put_line('错误');
  end if;
end;
--循环语句
declare
  v_i binary_integer := 1;
begin 
  loop
    dbms_output.put_line(v_i);
    v_i := v_i+1;
    exit when(v_i >10);
  end loop;
end;
    
declare
  v_i binary_integer := 1;
begin 
  while(v_i <11) loop
    dbms_output.put_line(v_i);
    v_i := v_i+1;
  end loop;
end;


declare
  v_i binary_integer := 1;
begin 
  for v_i in reverse 1..10 loop
    dbms_output.put_line(v_i);
  end loop;
end;
--异常处理
declare
  v_i binary_integer := 1;
begin 
  dbms_output.put_line(v_i/0);
exception
  when others then
  dbms_output.put_line('出错了');
end;