PL/SQL 基础知识简介

1.PL/SQL代码块
PL/SQL 代码块是指令的集合,支持所有的DML,NDS,DBMS_SQL,DDL。
    :DML 是数据操纵语言(Data Manipulation Language)包括,Insert ,update,delete
    : DDL是数据定义语言(Data Definition Language ),包括,Alter,create,drop,truncate,Grant,revoke
    : NDS本地动态SQL(Native Dynamic SQL)

 

2.PL/SQL代码块结构
    :声明部分 
    :执行部分 
    :异常处理部
--最小代码块
begin
    null;
end;
/

--匿名块
declare   --声明部分
    v_date_time timestamp;
begin     --执行部分
    select systimestramp
    into v_date_time
    from dual;
    DBMS_OUTPUT.PUT_LINE(v_date_time);
exception --异常处理部分
    when others
    then
        DBMS_OUTPUT.PUT_LINE(sqlerrm)
end;
/

/*
匿名块运行
1.在SQL windows 下 的 SQL>命令后面键入所有代码即可运行。
2.用cd进入这个脚本的保存目录
3.在PL/SQL用户界面运行
*/


--命名块
create or replace procedure CompoileError
    as
    v_timesramp timestramp;
    
begin
    select systimestamp
    into v_timesramp
    from duall;  --这是一张不存在的表
    
    DBMS_OUTPUT.PUT_LINE(v_timesramp);
exception
    when others
    then
        DBMS_OUTPUT.PUT_LINE(SQLERRM);
end;
/

/*
命名快通过编译,然后在数据库存储,然后执行
---因为调用不存在的表会编译错误
Warring:procedure created with complilation errors

查看错误信息
1.可以使用 show errors 语句 查看详细错误
  show errors
2.返回存储过程的代码及行号
    select line||' 'text procedure
    from user_source
    where name='CompoileError'
3. 执行查看错误
    exec CompoileError
*/

 

 

4.触发器
触发器是PL/SQL的一种特殊实现,他们存储在数据库中,但又不是存储过程或函数。由事件驱动,并且与执行在数据库的某种操作关联。
create or replace trigger author_tring
    after update of first_name
    on authors
    for each row
when(OLD.first_name!=NEW.first_name)
begin
    DBMS_OUTPUT.PUT_LINE(
        'First Name'
        ||:OLD.first_name
        ||'has change to'
        ||:NEW.first_name
        );
end;
/

当update first_name时,触发器被触发

update authors
set first_name='Roald'
where first_name='Ron'


--屏幕上会显示:
First Name Ron has change to Ronald

 

 

------------------------------------过程,函数的创建----------------------------

--创建存储过程
create or replace AddNewAuthor(
    P_ID authors.ID%TYPE,
    P_FirstName authors.first_name%TYPE,
    P_LasetName authors.last_name%TYPE 
    ) as
begin
     insert into authors(id,first_name,last_name)
     values(P_ID,P_FirstName,P_LasetName);
end AddNewAuthor;
/

--调用存储过程
begin
    AddNewAuthor(100,'Zelda','zudink');
end;


--创建函数
create or replace function ThreeAuthors(p_ISBN in books.isbn%TYPE)
return boolean as
v_Author3 books.authors3%TYPE

begin
select authors3
into v_Author3
from books
where isbn=p_ISBN;

if v_Author3 is null then
    return false;
else
    return true;
end if;

end ThreeAuthors;

--调用函数
begin
    for cur_rec in(select ISBN,title from books)loop
        if ThreeAuthors(cur_rec.ISBN) then
            DBMS_OUTPUT.PUT_LINE('""'||cur_rec||'"has 3 authors');
        end if;
    end loop;
end;
/

---过程和函数的删除
--drop procedure procedure_name;
drop procedure AddNewAuthor;
--drop function functionname;
drop function ThreeAuthors;

 

 

 

 

 

posted @ 2014-05-21 21:33  北门吹风  阅读(274)  评论(0编辑  收藏  举报