pl/sql简单执行记录个人学习记录

set SERVEROUTPUT ON --运行这个才有结果,否则书写pl\sql代码没有输出结果
--declare
  --声明的变量、类型、游标
begin
  --程序执行部分(类似main()方法)
  dbms_output.put_line('hello word');--相当于Console.WriteLine
--exception
  --针对于begin块中出现的异常,提供处理机制
  --when...then...
end;
declare
  --记录类型
  type a_record is record(
      v_col1_key1 varchar2(20),
      v_col1_key2 zzznew.key%type
  );
  v_col1_key1 varchar2(20):=0;--手动设置数据类型(默认取0)
  v_col1_key2 zzznew.key%type;--设置数据类型和某张表字段的数据类型相同
  v_a_record a_record;
begin
  select col1 into v_col1_key1 from zzznew where key='1' ;
  select col1 into v_col1_key2 from zzznew where key='2';
  dbms_output.put_line(v_col1_key1||'<.>'||v_col1_key2);
   --使用记录类型
  select col1,col2 into v_a_record from zzznew where key='1';
  dbms_output.put_line(v_a_record.v_col1_key1||'<O>'||v_a_record.v_col1_key2);
end;

 

declare
  v_zzznew_record zzznew%rowtype;--整行记录
  v_key zzznew.key%type :='';
begin
  select * into v_zzznew_record from zzznew where key='1';
  dbms_output.put_line(v_zzznew_record.col1||','||v_zzznew_record.col2);
end;

 

--pl/sql学习

if... then ... elsif... then... else... en if;

 

loop

 

 

 循环用while

 

 

 

--2~100之间的质数
declare
  v_i number(3):=2;
  v_j number(3):=2;
  v_flag number(1):=1;
begin
  while v_i<=100 loop
    v_j:=2;
    while v_j<=sqrt(v_i) loop
      if v_i mod v_j=0 then v_flag:=0;
      end if;
      v_j:=v_j+1;
    end loop;
    if v_flag=1 then dbms_output.put_line(v_i);
    end if;
    v_i:=v_i+1;  
    v_flag:=1;
  end loop;
end;

 

 

 

 

 goto

 

 

 

游标

declare
  --定义变量
  v_zzznew_key zzznew.key%type;
  --定义游标
  cursor zzznew_key_coursor is select key from zzznew;
begin
  --打开游标
  open zzznew_key_coursor;
  --提取游标
  fetch zzznew_key_coursor into v_zzznew_key;--相当于迭代地的next
  while zzznew_key_coursor%found loop --found相当于迭代器中hasnext()
    dbms_output.put_line(v_zzznew_key);
    fetch zzznew_key_coursor into v_zzznew_key;
  end loop;
  --关闭游标
  close zzznew_key_coursor;
end;

 

 

 

 

 游标推荐使用for循环,因为不需要打开、提取和关闭,在for里会自动的帮我们实现

 

 看来游标使用还是for循环好,非常简洁,但是使用while将更加清晰

 --按条件更新c

update zzznew set c=c+(case when c>10 then 1 when c<=10 then -1 else null end)
begin
  update zzznew set c=c+1 where c>10; 
  update zzznew set c=c-1 where c<=10; 
end;

 

begin
  update zzznew set c=c+(case when c>10 then 1 when c<=10 then -1 else null end);
end;

 

--游标其他的没记录,使用的时候去百度吧

 

接下来记录存储过程(没有返回值)与存储函数(有返回值)

--存储函数:

create or replace function ceshi(nu number) return varchar2 
is
  v_num number;
begin
  if nu>10 then v_num:=1;
  else v_num:=0;
  end if;
  return to_char(v_num);
end;
select ceshi(11) from dual --方法一

 

begin
  DBMS_OUTPUT.PUT_LINE(ceshi(11));  --方法二
END;

 使用:select get_sal(101) from dual;--获取101部门工资总和

 

OUT参数

 

【in】【out】【in out】

in相当于ref(默认)

out相当于out

in out相当于ref与o

 

 

 

 

 例子

 

 通过以上例子可以看出,out这种一般都是在pl/sql中可以输出,使用基本sql还找不出来

 

posted @ 2020-04-27 13:36  程序杰杰  阅读(236)  评论(0编辑  收藏  举报