Oracle触发器与存储过程

来源:互联网 发布:苏大网络统一身份认证 编辑:程序博客网 时间:2024/04/30 10:24
  首先我们来先讲讲触发器,后面再讲存储过程
触发器
是特定事件出现的时候,自动执行的代码块。类似于存储过程,但是用户不能直接调用他们。
功能:
1、 允许/限制对表的修改
2、 自动生成派生列,比如自增字段
3、 强制数据一致性
4、 提供审计和日志记录
5、 防止无效的事务处理
6、 启用复杂的业务逻辑
开始
create trigger biufer_employees_department_id
       before insert or update
              of department_id
             on employees
       referencing old as old_value
                       new as new_value
       for each row
       when (new_value.department_id<>80 )
begin
       :new_value.commission_pct :=0;
end;
/
触发器的组成部分:
1、 触发器名称
2、 触发语句
3、 触发器限制
4、 触发操作
 
1、 触发器名称
create trigger biufer_employees_department_id
命名习惯:
biufer(before insert update for each row)
employees 表名
department_id 列名

2、 触发语句
比如:表或视图上的DML语句、DDL语句、数据库关闭或启动,startup shutdown 等等
before insert or update
              of department_id
             on employees
       referencing old as old_value
                       new as new_value
       for each row
说明:
1、 无论是否规定了department_id ,对employees表进行insert的时候
2、 对employees表的department_id列进行update的时候
3、 触发器限制
when (new_value.department_id<>80 )
限制不是必须的。此例表示如果列department_id不等于80的时候,触发器就会执行。
其中的new_value是代表更新之后的值。
4、 触发操作
是触发器的主体
begin
       :new_value.commission_pct :=0;
end;
主体很简单,就是将更新后的commission_pct列置为0
触发:
insert into employees(employee_id,
last_name,first_name,hire_date,job_id,email,department_id,salary,commission_pct )
values( 12345,’Chen’,’Donny’, sysdate, 12, ‘donny@hotmail.com’,60,10000,.25);
select commission_pct from employees where employee_id=12345;
触发器不会通知用户,便改变了用户的输入值。
触发器类型:
1、 语句触发器
2、 行触发器
3、 INSTEAD OF 触发器
4、 系统条件触发器
5、 用户事件触发器
1、 语句触发器
是在表上或者某些情况下的视图上执行的特定语句或者语句组上的触发器。能够与INSERT、UPDATE、DELETE或者
组合上进行关联。但是无论使用什么样的组合,各个语句触发器都只会针对指定语句激活一次。比如,无论
update多少行,也只会调用一次update语句触发器。
例子:
需要对在表上进行DML操作的用户进行安全检查,看是否具有合适的特权。
Create table foo(a number);
Create trigger biud_foo
       Before insert or update or delete
              On foo
Begin
       If user not in (‘DONNY’) then
              Raise_application_error(-20001, ‘You don’t have access to modify this table.’);
       End if;
End;
/
即使SYS,SYSTEM用户也不能修改foo表
[试验]
对修改表的时间、人物进行日志记录。
1、 建立试验表
create table employees_copy as select * from hr.employees
2、 建立日志表
create table employees_log(
        who varchar2(30),
       when date);
3、 在employees_copy表上建立语句触发器,在触发器中填充employees_log 表。
Create or replace trigger biud_employee_copy
              Before insert or update or delete
                     On employees_copy
       Begin
              Insert into employees_log(Who,when)
              Values( user, sysdate);     
       End;
       /
4、 测试
update employees_copy set salary= salary*1.1;
select * from employess_log;
5、 确定是哪个语句起作用?
即是INSERT/UPDATE/DELETE中的哪一个触发了触发器?
可以在触发器中使用INSERTING / UPDATING / DELETING 条件谓词,作判断:
begin
        if inserting then
               -----
        elsif updating then
              -----
        elsif deleting then
               ------
        end if;
end;
if updating(‘COL1’) or updating(‘COL2’) then
        ------
end if;
[试验]
1、 修改日志表
alter table employees_log
        add (action varchar2(20));
2、 修改触发器,以便记录语句类型。
Create or replace trigger biud_employee_copy
              Before insert or update or delete
                     On employees_copy
       Declare
              L_action employees_log.action%type;
       Begin
        if inserting then
               l_action:=’Insert’;
        elsif updating then
               l_action:=’Update’;
        elsif deleting then
               l_action:=’Delete’;
        else
               raise_application_error(-20001,’You should never ever get this error.’);
              Insert into employees_log(Who,action,when)
              Values( user, l_action,sysdate);
       End;
       /
3、 测试
insert into employees_copy( employee_id, last_name, email, hire_date, job_id)
       values(12345,’Chen’,’Donny@hotmail’,sysdate,12);
select * from employees_log
 
oracle 存储过程的基本语法
iTbulo.COM 2007-4-19 动态网站制作指南(1834)
 
1.基本结构
CREATE OR REPLACE PROCEDURE 存储过程名字
(
    参数1 IN NUMBER,
    参数2 IN NUMBER
) IS
变量1 INTEGER :=0;
变量2 DATE;
BEGIN
END 存储过程名字
2.SELECT INTO STATEMENT
  将select查询的结果存入到变量中,可以同时将多个列存储多个变量中,必须有一条
  记录,否则抛出异常(如果没有记录抛出NO_DATA_FOUND)
  例子:
  BEGIN
  SELECT col1,col2 into 变量1,变量2 FROM typestruct where xxx;
  EXCEPTION
  WHEN NO_DATA_FOUND THEN
      xxxx;
  END;
  ...
3.IF 判断
  IF V_TEST=1 THEN
    BEGIN
       do something
    END;
  END IF;
4.while 循环
  WHILE V_TEST=1 LOOP
  BEGIN
 XXXX
  END;
  END LOOP;
5.变量赋值
  V_TEST := 123;
6.用for in 使用cursor
  ...
  IS
  CURSOR cur IS SELECT * FROM xxx;
  BEGIN
 FOR cur_result in cur LOOP
  BEGIN
   V_SUM :=cur_result.列名1+cur_result.列名2
  END;
 END LOOP;
  END;
7.带参数的cursor
  CURSOR C_USER(C_ID NUMBER) IS SELECT NAME FROM USER WHERE TYPEID=C_ID;
  OPEN C_USER(变量值);
  LOOP
 FETCH C_USER INTO V_NAME;
 EXIT FETCH C_USER%NOTFOUND;
    do something
  END LOOP;
  CLOSE C_USER;
8.用pl/sql developer debug
  连接数据库后建立一个Test WINDOW
  在窗口输入调用SP的代码,F9开始debug,CTRL+N单步调试
 
存储过程基本的语法都已经讲过了,是不是很想试试手啊,不急,我们来看看下面的:
【转自】http://www.cnblogs.com/AXzhz/archive/2006/09/20/510007.html
①为什么要使用存储过程?
因为它比SQL语句执行快.
②存储过程是什么?
把一堆SQL语句罗在一起,还可以根据条件执行不通SQL语句.(AX写作本文时观点)
③来一个最简单的存储过程
CREATE PROCEDURE dbo.testProcedure_AX
AS
select userID from USERS order by userid desc
注:dbo.testProcedure_AX是你创建的存储过程名,可以改为:AXzhz等,别跟关键字冲突就行了.AS下面就是一条SQL语句,不会写SQL语句的请回避.
④我怎么在ASP.NET中调用这个存储过程?
下面黄底的这两行就够使了.
        public static string GetCustomerCName(ref ArrayList arrayCName,ref ArrayList arrayID)
        {
            SqlConnection con=ADConnection.createConnection();
            SqlCommand cmd=new SqlCommand("testProcedure_AX",con);
            cmd.CommandType=CommandType.StoredProcedure;
            con.Open();
            try
            {
                SqlDataReader dr=cmd.ExecuteReader();
                while(dr.Read())
                {
                    if(dr[0].ToString()=="")
                    {
                        arrayCName.Add(dr[1].ToString());
                    }
                }
                con.Close();
                return "OK!";
            }
            catch(Exception ex)
            {
                con.Close();
                return ex.ToString();
            }
        }
注:其实就是把以前
SqlCommand cmd=new SqlCommand("select userID from USERS order by userid desc",con);
中的SQL语句替换为存储过程名,再把cmd的类型标注为CommandType.StoredProcedure(存储过程)
⑤写个带参数的存储过程吧,上面这个简单得有点惨不忍睹,不过还是蛮实用的.
参数带就带两,一个的没面子,太小家子气了.
CREATE PROCEDURE dbo.AXzhz
/*
这里写注释
*/
@startDate varchar(16),
@endDate varchar(16)
AS
 select id  from table_AX where commentDateTime>@startDate and commentDateTime<@endDate order by contentownerid DESC
注:@startDate varchar(16)是声明@startDate 这个变量,多个变量名间用【,】隔开.后面的SQL就可以使用这个变量了.
⑥我怎么在ASP.NET中调用这个带参数的存储过程?
 public static string GetCustomerCNameCount(string startDate,string endDate,ref DataSet ds)
{
            SqlConnection con=ADConnection.createConnection();
//-----------------------注意这一段--------------------------------------------------------------
            SqlDataAdapter da=new SqlDataAdapter("AXzhz",con);
            para0=new SqlParameter("@startDate",startDate);
            para1=new SqlParameter("@endDate",endDate);
            da.SelectCommand.Parameters.Add(para0);
            da.SelectCommand.Parameters.Add(para1);
            da.SelectCommand.CommandType=CommandType.StoredProcedure;
//-----------------------------------------------------------------------------------------------
            try
            {
                con.Open();
                da.Fill(ds);
                con.Close();
                return "OK";
            }
            catch(Exception ex)
            {
                return ex.ToString();
            }           
        }
注:把命令的参数添加进去,就OK了
鸟的,改字体颜色的东西太垃圾了,改不好,大家凑活着看.
⑦我还想看看SQL命令执行成功了没有.
注意看下面三行红色的语句
CREATE PROCEDURE dbo.AXzhz
/*
  @parameter1 用户名
  @parameter2 新密码
*/
@password nvarchar(20),
@userName nvarchar(20)
AS
declare @err0 int
update WL_user set password=@password where UserName=@userName
set @err0=@@error
select  @err0 as err0
注:先声明一个整型变量@err0,再给其赋值为@@error(这个是系统自动给出的语句是否执行成功,0为成功,其它为失败),最后通过select把它选择出来,某位高人说可以通过Return返回,超出本人的认知范围,俺暂时不会,以后再补充吧
⑧那怎么从后台获得这个执行成功与否的值呢?
下面这段代码可以告诉你答案:
    public static string GetCustomerCName()
        {
            SqlConnection con=ADConnection.createConnection();
 
            SqlCommand cmd=new SqlCommand("AXzhz",con);
            cmd.CommandType=CommandType.StoredProcedure;
            para0=new SqlParameter("@startDate","2006-9-10");
            para1=new SqlParameter("@endDate","2006-9-20");
            da.SelectCommand.Parameters.Add(para0);
            da.SelectCommand.Parameters.Add(para1);
            con.Open();
            try
            {
               Int32 re=(int32)cmd.ExecuteScalar();
                con.Close();
                if (re==0)
                 return "OK!";
                else
                 return "false";
            }
            catch(Exception ex)
            {
                con.Close();
                return ex.ToString();
            }
        }
注:就是通过SqlCommand的ExecuteScalar()方法取回这个值,这句话是从MSDN上找的,俺认为改成:
     int re=(int)cmd.ExecuteScalar();  99%正确,现在没时间验证,期待您的测试!!!
⑨我要根据传入的参数判断执行哪条SQL语句!!~
下面这个存储过程可以满足我们的要求,竟然是Pascal/VB的写法,Begin----End ,不是{},,,对使用C#的我来说,这个语法有点恶心.........
ALTER PROCEDURE dbo.selectCustomerCNameCount
@customerID int
AS
if @customerID=-1
 begin
 select contentownerid ,userCName,count(*) as countAll from view_usercomment group by contentownerid,userCName order by contentownerid DESC
 end
else
 begin
 select contentownerid ,userCName,count(*) as countAll from view_usercomment where contentownerid=@customerID group by contentownerid,userCName order by contentownerid DESC
 end
好了,俺的水平只止于此,也够菜鸟们喝一壶的了,还有更多东西等着我们去发现,无尽的征途!!!!!!!!!!!
 
下面是存储过程的调用方式:

存储过程 包含三部分: 声明,执行部分,异常。

可以有无参数程序和带参数存储过程。

无参程序语法

1 create or replace procedure NoParPro
2 as  ;
3 begin
4 ;
5 exception
6     ;
7 end;
8 

   带参存储过程实例

 1 create or replace procedure queryempname(sfindno emp.empno%type) as
 2        sName emp.ename%type;
 3        sjob emp.job%type;
 4 begin
 5        ....
 7 exception
          ....
14 end;
15 

   带参数存储过程含赋值方式
 1 create or replace procedure runbyparmeters  (isal in emp.sal%type,
                            sname out 
varchar,sjob in out varchar)
 2  as icount number;
 3  begin
 4       select count(*into icount from emp where sal>isal and job=sjob;
 5       if icount=1 then
 6         ....
 9       else
10         ....
12       end if;
13  exception
14       when too_many_rows then
15       DBMS_OUTPUT.PUT_LINE('返回值多于1行');
16       when others then
17       DBMS_OUTPUT.PUT_LINE('在RUNBYPARMETERS过程中出错!');
18  end;
19 

  过程调用
 
方式一
 1 declare
 2        realsal emp.sal%type;
 3        realname varchar(40);
 4        realjob varchar(40);
 5  begin
 6        realsal:=1100;
 7        realname:='';
 8        realjob:='CLERK';
 9        runbyparmeters(realsal,realname,realjob);     --必须按顺序
10        DBMS_OUTPUT.PUT_LINE(REALNAME||'   '||REALJOB);
11  END;
12 

  方式二
 1 declare
 2       realsal emp.sal%type;
 3       realname varchar(40);
 4       realjob varchar(40);
 5 begin
 6       realsal:=1100;
 7       realname:='';
 8       realjob:='CLERK';
 9       runbyparmeters(sname=>realname,isal=>realsal,sjob=>realjob);  --指定值对应变量顺序可变
10       DBMS_OUTPUT.PUT_LINE(REALNAME||'   '||REALJOB);
11 END;
12 
 
感兴趣的,推荐去itpub下载《Oracle触发器与存储过程高级编程-第3版itpub.pdf》一读!你也是高手!
  在sql*plus中:  
  declare  
      --必要的变量声明,视你的过程而定  
  begin  
      execute   过程名(parameter1,parameter2,...);  
  end  
  / 
  
  还有就是: execute immediate 'CALL ProcedureName()';
 
  pl/sql中怎样调用其他用户中的存储过程:
     usera   中的proc1  
   
    如果在userb中写存储过程  
      create   or   replace   procedure   proc2()   is  
      begin  
        usera.proc1;  
      end   pro_select;  
     会报错。   
       error:   pls-00201:   必须说明标识符   usera.proc1   
   
   当然可以了,只要usera授予userb执行权限。  
  1、以usera连接oracle  
  2、sql>grant   execute   on   proc1   to   userb;
原创粉丝点击