﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>语源科技BlogJava-Richard</title><link>http://www.blogjava.net/kevinfriend/</link><description /><language>zh-cn</language><lastBuildDate>Tue, 14 Apr 2026 15:06:49 GMT</lastBuildDate><pubDate>Tue, 14 Apr 2026 15:06:49 GMT</pubDate><ttl>60</ttl><item><title>Manager User</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/12/74716.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Thu, 12 Oct 2006 01:49:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/12/74716.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74716.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/12/74716.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74716.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74716.html</trackback:ping><description><![CDATA[
		<p>create user test1 identified by test1;<br />grant connect,create table to test1;<br />conn <a href="mailto:cyts_cc/cyts_cc@orcl2000">cyts_cc/cyts_cc@orcl2000</a>;<br />create table(<br />id int)<br />tablespace user;<br />ERROR 位于第 1 行:<br />ORA-01950: 表空间'USERS'中无权限<br />conn <a href="mailto:cyts_cc/cyts_cc@orcl2000">cyts_cc/cyts_cc@orcl2000</a>;<br />alter user test1 quota 1M on users;<br />create tab<br />(id int);<br />success<br />alter user test1 account lock;<br />conn <a href="mailto:test1/test1@orcl2000">test1/test1@orcl2000</a>;<br />ERROR:<br />ORA-28000: the account is locked<br />1 Database Schema<br /> a schema is a named collection of objects<br /> b user is created and a corresponding schema is created<br /> c user can be associated only with one schema<br /> d username and schema are often userd interchangely.<br />2 Checklist for creating users<br />  a idntfigy tablespaces in which the usr nedds to store objects<br />  b decide on quotas for each tablespace<br />  c assign a default tablespace and temporary tablespace.if you do not specify at the time of create user,system tablespace will be the defalut tablespace and temporary.it will affect the performance of the oralce.<br />  d create user<br />  e grant privileges and roles to user<br />  desc dba_users;<br />  select * from dba_users;<br />3 Creating a new user:<br />Database Authentiacation<br /> set the initial password<br />  create user aaron<br />  identified by soccer<br />  default tablespace data<br />  temporary tablespace temp<br />  guota 15m on data<br />  password expire;</p>
		<p>  alter database default temporary tablespace temp;<br />4 Creating a new user operating System Authentication<br />  os_authent_prefix initialllization parameter specifies the format of the username<br />  defauts to ops$<br />    create user arron<br />    identified externally<br />    default tablespace users<br />    temporary tablespace temp<br />    quota 15m on data<br />    password expire;</p>
		<p>    conn / <br />    show parameter os<br />    os_authent_prefix                    string                           OPS$<br />    create user ops$test3<br />      identified externally<br />      default tablespace us<br />      temporary tablespace <br />      quota 10m on users<br />    thee test2 is an user of os ,which the oracle is installed.<br />5 Changing user quota on tablespace<br /> alter user test3 quota 4m on users;<br /> you cann't grant quota on temp and undotbs.<br /> <br /> alter quota 0 on uers -- means that no new table space can be allocated and cannot change the exist object in the tablespaces<br />6 drop user<br /> you cannot drop user who has connected to oracle<br />  drop user (cascade)<br />7 Obtaining User information<br /> information about uers can be obtained by qerying the data dictionary<br />  dba_users<br />  名称                           <br />-----------------------------<br />USERNAME                       <br />USER_ID                        <br />PASSWORD                       <br />ACCOUNT_STATUS                 <br />LOCK_DATE                      <br />EXPIRY_DATE                    <br />DEFAULT_TABLESPACE             <br />TEMPORARY_TABLESPACE           <br />CREATED                        <br />PROFILE                        <br />INITIAL_RSRC_CONSUMER_GROUP    <br />EXTERNAL_NAME                  <br />  dba_ts_quotas<br />   名称           <br /> ---------------<br /> TABLESPACE_NAME<br /> USERNAME       <br /> BYTES          <br /> MAX_BYTES      <br /> BLOCKS         <br /> MAX_BLOCKS     </p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74716.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-12 09:49 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/12/74716.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Using SET Operators.</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74565.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:51:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74565.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74565.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74565.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74565.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74565.html</trackback:ping><description><![CDATA[
		<p>1 The Union Operator<br /> The union operator returns results form both queries after eliminating duplications.\<br /> select employee_id,job_id<br /> from employees<br /> uniion<br /> select employ_id ,job_id<br /> from job_history;<br />2 the all operator<br /> The union all opertor reutrn result from both queries,including all duplications<br />3 interset<br /> select ster_id,qty from sales where qty&gt;20;<br /> intersect<br /> select ster_id,qty from sales where ster_id like '7%';<br />4 minus<br /> select ster_id,qty from sales where qty&gt;20<br /> minus<br /> select ster_id from sales where ster_id like '7%'</p>
		<p>5 set operator guidelines<br /> . teh expressions in the select list must match in number and data type;<br /> . Parentheses can be used to alter the sequence of the execution<br /> .The order by clause:<br />    can appear only at the very end of the statement<br />    will accept the column name,aliases from thee firest select statement ,or thee positional notation<br /> .Duplicate row are atuomatically eliminated except in union all.<br /> .Column names from the first query appear in the result<br /> .The output is sorted in ascending order by default except in union all<br />6 matching the select statement<br /> select department_id,to_number(null),location,hire_date<br /> from employees<br /> union<br /> select department_id,location_id,to_date(null)<br /> from departments;</p>
		<p> select employee_id,job_id,salary<br /> from employees<br /> union<br /> select employee_id,job_id,0<br /> from job_history;<br />7 Controlling the order of the rows<br /> select 'sing' as "my dream" ,3,a_dummy<br /> from dual<br /> union<br /> select 'like''d like to teach',1<br /> from dual<br /> union<br /> select 'the world to',2 <br /> from dual<br /> order by 2;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74565.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:51 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74565.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>开发子过程</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74564.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:51:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74564.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74564.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74564.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74564.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74564.html</trackback:ping><description><![CDATA[
		<p> 1  开发过程<br /> 1) 建立过程：不带参数<br />  create or replace procedure out_time<br />  is<br />  begin<br />    dbms_output.put_line(systimestamp);<br />  end;<br />  a 使用execute 命令调用过程<br />   set  serveroutput on<br />   exec out_time;<br />  b 使用call 命令调用过程<br />   set serveroutput on<br />   call out_time();<br /> 2) 建立过程：带有in参数 默认为输入参数，另外也可以使用in 关键子显示的定义<br />   create or replace procedure add_employee<br />   (eno number,name varchar2,sal number,<br />    job varchar default 'clerk',dno number)<br />   is<br />   e_integrity exception;<br />   pragma exception_init(e_intgegrity,-2291);<br />   begin<br />    insert into emp(empno,ename,sal,job.deptno)<br />      values(eno.name,sal,job,dno);<br />    exception<br />      when dup_val_on_index then<br />        raise_application_error(-20000,'雇员号不能重复');<br />      when e_integrity then<br />        raise_application_error(-20001,'部门号不存在');<br />    <br />调用<br />   exec add_employee(111,'clark',200,'manager',10);<br />   3 建立过程，带有out 参数<br />    create or replcace procedure query_employee<br />    (eno number,name out varchar2,salary out number)<br />    is<br />    begin<br />      select ename,sal,into name,salary from emp where empno=eno;<br />    exception<br />      when no_data_found then<br />        raise_application_error(-20000,'G该雇员不存在');<br />    end; <br />    <br />    调用<br />    var name varchar2(10)<br />    var salary number<br />    exec query_employee(7788,:name,:salary);<br />    print name,salary;<br />    4 建立过程，带有in out 参数<br />    create or replace procedure compute<br />    (num1,in out number,num2 in out number)<br />    is <br />       v1 number;<br />       v2 number;<br />    begin<br />      v1:=num1/num2;<br />      v2:=mod(num1,num2);<br />      num1:=v1;<br />      num2:=v2;<br />    end; <br />    <br />    调用<br />    var n1 number<br />    var n2 number<br />    exec :n1:=100;<br />    exec :n2:=30<br />    exec compute(:n1,:n2)<br />    print n1 n2<br />    5) 为参数传递变量和数据 位置传递，名称传递，组合传递<br />    create or replace procedure add_dept<br />    (dno number,dname varchar2 default null,loc varchar default null)<br />    is <br />    begin<br />      insert into dept values(dno.dname,loc);<br />    end;<br />    -- 位置传递<br />     exec add_dept(50,'sales','new york');<br />     exec add_dept(60);<br />     exec add_dept(70,'admin');<br />    -- 名称传递<br />     exec add_dept(50,loc=&gt;'new york');<br />     exec add_dept(60,dname=&gt;'sales',loc=&gt;'new york');<br />   6) 显示当前用户的所有程序及其源代码<br />     select text from user_source where name='add_dept';<br />   7) 删除过程<br />     drop procedure add_dept;<br />2 开发函数<br />  可以在sql语句和其他子过程中执行。<br />  1 建立函数，不带任何参数<br />  create or replace function get_user<br />  return varchar2<br />  is<br />    v_user varchar2(100);<br />  begin<br />    select username into v_user from user_users;<br />    return v_user;<br />    end;<br />  --使用变量接收函数返回值<br />   var v2 varchar2(100)<br />   exec :v1:=get_user<br />   print v1;<br /> -- 在sql 语句中直接调用函数<br />   select get_user from dual;<br /> -- 使用dbms_output 调用函数<br />   set serveroutput on<br />   exec dbms_output.put_line('get_user');<br /> 2) 建立函数，带有in 参数<br />   create or replace function get_sal(name in varchar2)<br />   reutnr number<br />   as<br />   v_sal emp.sal%type;<br />   begin<br />     select sal into v_sal from emp where upper(ename)=upper(name);<br />     return v_sal;<br />   exception<br />     when no_data_found then<br />       raise_application_error(-20000,'employee does not exist');<br />   end;<br /> 3) 建立函数，带有out 参数<br />   create or replace function get_info<br />   (name varchar2,title out varchar2)<br />   return varchar2<br />   as<br />     deptname dept.dname%type;<br />   begin<br />     select a,job,b,dname into title,deptname from emp a,dept b<br />     where a.deptno=b.deptno<br />     and upper(a.ename)=uppder(name);<br />     return deptname;<br />   end;<br />   var job varchar2(20)<br />   var dname varchar2(20)<br />   exec :dname:=get_info('scott',job);<br />   print dname job</p>
		<p> 4) 带有 in out 参数<br />  create or replace function result<br />  (num1,number,num2 in out nu8mber)<br />  return number<br />  as<br />    v_result number(6);<br />    v_remainder number;<br />  begin<br />    v_result:=num1/num2;<br />    v_remainder:=mod(num1,num2);<br />    num2:=v_remainder;<br />    retrun v_result;<br />  exception <br />    when zero_divide then<br />       raise_application_error(-20000,'zero divied');<br />  end;<br /> 5) 函数调用的限制<br />  -- 在sql 语句中只能调用存储函数<br />  -- 在sql 语句中只能调用带有输入参数in ，而不能有输出参数out 和in out 参数的函数<br />  -- 在sql 语句中调用的函数的参数必须是标准的sql 数据类型，不能是pl/sql 所特有的数据类型<br />  -- 在sql 语句中调用的函数不能包含insert，update 和delete<br /> 6) 查看源代码<br />  set pagesize 40<br />  select text form user_source where name='result';<br /> 7) 删除函数<br />  drop function result;<br /> 3 管理子程序<br />  1) 列出当前用户的子程序<br />   select object_name,created,status form user_objects<br />   where object_type in ('procedure','function');<br />  2)列出子程序源代码<br />   select text from user_sorce where name='raise_salary'<br />  3)类出子程序编译错误<br />    -- show errors<br />    --使用数据字典user_errors  确定错误原因和位置<br />     select line||'/'||position as "line/col",text error<br />     from user_errors where name='raise_salary';<br />   4) 列出对象的依赖关系<br />    -- 使用 user_dependenciess 确定直接依赖关系<br />    select name,type from user_dependencies<br />    where referenced_name='emp'<br />    -- 使用 deptree 和 ideptree 确定依赖和见解依赖关系<br />    select nested_level,name,type from deptree;<br />   5) 重新编译子程序<br />     当被应用对象的结构被修改以后，就会将相关依赖对象转变为无效invalid ，需要重新编译<br />     1<br />     alter table emp add remark varchar2(100);<br />     2<br />     select object_name,object_type from user_objects<br />     where status='invalid'<br />     3<br />     alter procedure add_employee compile;<br />     alter view dept10 compile;<br />     alter function get_info compile;<br />      <br />   </p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74564.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:51 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74564.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>处理例外</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74563.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:46:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74563.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74563.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74563.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74563.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74563.html</trackback:ping><description><![CDATA[
		<p>1例外简介<br /> 1） 例外分类<br />  预定义分类，非预定义分类，自定义例外。<br />2 处理预定义例外<br />  1) 常用预定义例外<br />   a access_into_null;<br />     create type emp_type as object<br />     (name varchar2(2),sal number(6,2));<br />     <br />     declare<br />       emp emp_type;<br />     begin<br />       emp.name:='scott';<br />     exception<br />       when access_into_null then<br />          dbms_output.put_line('首先初始化对象emp');<br />    b case_not_found<br />     undef no<br />     declare<br />       v_val emp.sal%type;<br />     begin<br />       select sal into v_sal from emp where empno=&amp;no;<br />       case<br />         when v_sal&lt;1000 then<br />           update emp set sal=sal+100 where empno=&amp;no;<br />         when v_sal&lt;2000 then<br />           update emp set sal=sal+150 where empno=&amp;no;<br />         when v_sal&lt;3000 then<br />          update emp set sal=sal+200 where empno=&amp;no;<br />       end case;<br />       exception<br />         when case_not_found then<br />           dbms_output.put_line();<br />      end;<br />    c collection is null<br />    在给集合元素（嵌套表或array类型）赋值前，必须首先初始化集合元素<br />    declare type ename_table_type is table of emp.eanme%type;<br />    ename_table ename_table_type;<br />    begin<br />      select e_name into ename_talbe(2) from emp where empno=$no;<br />    exception<br />      when collection_is_null then<br />        dbms_output.put_lilne('必须使用构造方法初始化集合元素');<br />    end;<br />    d currsor_already_open <br />    reopen curosr 如果用户已经使用了open 命令打开了显示游标，或执行for循环(隐式的打开游标)<br />       delcare<br />         cursor emp_surosr is select ename,sal,from emp;<br />       begin<br />         open emp_curosr;<br />         for emp_record in emp_cursor loop<br />              dbms_output.put_line(emp_record.eanme);<br />         end loop;<br />       exception<br />          when cursor_already_open then<br />            dbms_output.put_line("游标已经打开");<br />       end;<br />     e dup_val_on_index<br />     begin<br />     exception<br />        when dup_val_on_index then<br />        dbms_output.put_line("列上不能出现重复值");<br />     end;<br />     d invalid_curosr<br />     delcare<br />       curosr emp_cursor is select ename,sla from emp;<br />       emp_record emp_crusor%rowtype;<br />     begin<br />       fetch emp_cursor into emp_record;<br />       close emp_crusro;<br />     exception<br />       dbms_output.put_line("游标没有打开");<br />     end;<br />     f invalid_number  can not convert char to nmuber successfully<br />       begin<br />         update mep set sal=sal+1oo;<br />       exception<br />         when invalid_number then<br />     g no_data_found  when select into is executed ,no row is returned      <br />       declare<br />         v_sal emp.sal%type;<br />       begin<br />          select sal into v_cal form emp where lower(ename)=lower('&amp;name');<br />       exception<br />         when no_data_found then<br />             dbms_output.put_line('没有返回结果');<br />       end;<br />      h too_many_row  ora -01422 there are too many are return when "select into" is executed<br />      i zero_divide ora-01476<br />      g subscript_beyond_count ora-065533<br />      declare<br />        type emp_array_type is varray(20) of varchar2(10);<br />        emp_array emp_array_type;<br />      begin<br />         emp_array:=emp_array_type('scott','mary');<br />         dbms_output.put_line('emp_array(3)');<br />      exception<br />         when subscript_beyone_count then<br />          dbms_out.put_line('超出下标范围');<br />      end;<br />      k subscript_outside_limit<br />       emp_array(-1);<br />      l value_error the length of variable cannot contain the actual value;<br />      declare<br />      begin<br />      end;<br />3 处理非预定义例外<br />  delcare<br />    e_integrity exception;<br />    pragma exception_init(e_integrity,-2291);<br />  begin<br />    update emp set deptno=dno where empno=&amp;no;<br />  exception<br />    when a_integrity then<br />  end;<br />4 处理自定义例外<br />  与oracle 错误没有任何联系，为业务逻辑所定义的例外<br />  delcare<br />    e_no_employee exception;<br />  begin<br />    update emp set deptno=&amp;dno where empno=&amp;eno;<br />  if sql%notfound then<br />    raise e_no_employee;<br />  end if;<br />  exception<br />    when e_no_emplyee then<br />     dbms_output.put_line('该雇员不存在');<br />5 使用错误例外函数<br />  使用例外函数可以取得错误号以及相关的错误消息，sqlcode 用于取得oracle 的错误号，而sqlerrm<br />则用于取得与之相关的错误信息。<br />  1 sqlcode 和 sqlerrm<br />  为了在pl/sql 应用程序中处理其他为预料的到的oracle 错误，用户可以在例外处理部分的<br />when others 自句后，引用两个函数<br />  declare<br />    v_ename emp.ename%type;<br />  begin<br />    select ename into v_ename form emp where sal='&amp;v_sal';<br />  exception<br />    when no_data_found then<br />    when others then<br />       dbms_output.put_line(sqlcode);<br />       dbms_output.put_line(sqlerrm);<br />  end;<br />  2 raise_aaplicaition_error<br />   只能在子程序中使用（过程，函数，包，触发器）<br />   raise_application_error(error_number,message,[true|false]);<br />   error_number 错误号，在－20000到－20999 之间<br />   message 指定错误消息，不能超过2048 <br />   if v_comm is null then<br />       raise_application_error(-20001,'该雇员无补助');<br />   end if;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74563.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:46 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74563.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>开发包</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74562.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:46:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74562.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74562.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74562.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74562.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74562.html</trackback:ping><description><![CDATA[1建立包<br /> 1) 建立包规范： 用于定义包的公共组建，包括常量，变量，游标，过程和函数等<br /> create or replace package emp_package is<br />  g_deptno number(3):=30;<br />  procedure add_employee(eno number,name varchar2,salary number dno number default g_deptno);<br />  procedure fire_empoyee(eno number);<br />  function get_sal(eno number) return number;<br /> end emp_package;<br />  2) 建立包体<br />   用于实现包规范所定义的过程和函数。在包体中也可以单独定义私有组件，包括变量，常量，过程和函数等。但在包体中所定义的组件只能在包内使用，而不能由其他子程序引用。<br />   create or replace package body emp_package is<br />    function validate_deptno(v_deptno number)<br />      return boolean;<br />    is<br />      v_temp int;<br />    begin<br />      select 1 into v_temp from dept where deptno=v_deptno;<br />      return true;<br />    exception<br />      when no_data_found then<br />       return false;<br />    end;<br />    procedure add_employee(eno number,name varchar2,salary number,dno number default g_deptno)<br />    is<br />    begin<br />      if validate_deptno(dno) then<br />        insert into emp(empno,ename,sal,deptno)<br />         values(eno,name,salary,dno);<br />      esle<br />        raise_application_error(-20011,'部门不存在');<br />      end if;<br />    exception<br />      when dup_val_on_index then<br />        raise_application_error(-20011,'该雇员已存在')<br />    end;<br />    procedure fire_employee(eno number) is<br />    begin<br />      select from emp where empno=eno;<br />      if sql%notfound then<br />         raise application_error(-20012,'');<br />      end if;<br />    end;<br />   function get_sal(eno number) return number<br />   is<br />     v_sal emp.sal%type;<br />   begin<br />     select sal into v_sal from emp where empno=eno;<br />     return v_sal;<br />   exception<br />     when no_data_found then<br />       raise_application_error(-200012,'');<br />   end;<br />  end emp_package;<br />  3) 调用包组建<br />    －－ 在同一个包内调用组建 不需要加包名前缀，直接调用<br />  create or replace paclage body emp_package is<br />    procedure add_employee(eno number,name varchar2,salary number,dno number default g_deptno)<br />    is<br />    begin<br />      validate_deptno(dno) then<br />    exception<br />    end;<br />   -- 调用包公用变量<br />   exec emp_package.g_deptno:=20<br />   -- 调用公用过程<br />   exec emp_package.add_employee(111,'mary,2000');<br />   -- 调用远程数据库包的公用组件<br />   exec <a href="mailto:emp_paclage.add_employee@orasrv(1116,'scott',1200">emp_paclage.add_employee@orasrv(1116,'scott',1200</a>);<br />   4) 查看包源代码<br />   select text from user_source where name='emp_package' and type='package';<br />   5) 删除包<br />   drop packagee emp_package;<br />2 使用包重载<br />  指多个具有相同名字的子程序，在调用的时候使用不同的参数传递。<br />  1) 建立包规范<br />   同名过程和函数必须具有不同的输入参数，但同名函数返回值的类型数据必须相同<br />    create or replace package overload is<br />    function get_sal(eno number) return number;<br />    function get_sal(name varchar2) return number;<br />    procedure fire_employee(eno number);<br />    procedure fire_employee(name varchar2);<br />   2) 建立包体<br />    。。。<br />3) 使用包构造过程<br /> 初始化全局变量<br /> 1 建立包规范<br />   create or replace packiage emp_package<br />   is<br />   minsal number(6,2);<br />   maxsal number(6,2);<br />   procedure upd_sal(eno number,salary number);<br />   procedure upd_sal(name varhcar2,salary number);<br />   end;-- 定义了两全局变量和三个公用过程<br />   2 建立包体<br />    create or replace package body emp_package is<br />      procedure add_employee(cno number,name varchar2,salary number,dno number)<br />      is<br />      begin<br />        if salary between minsal and maxsal then<br />          insert into emp(empno,ename,sal,deptno)<br />         ........<br />    -- 构造过程，位于子程序尾部，已begin 开始已end 结束<br />     begin<br />       select min(sal),max(sal) into minsal,maxsal from emp;<br />     end;<br />      end;<br />3 调用包公用组建<br />   在同一次会话中第一次调用包的公用组建时，会自动执行其它构造函数，而将来调用其他组建时则不会再调用其构造过程。<br />4 使用纯度级别<br /> 1 家里包规范<br />  create or replcace package purity is<br />  minsal number(6,2);<br />  maxsal number(6,2);<br />  function max_sal return number;<br />  function min_sal return number;<br />  pragma restrict_references(max_sal,wnps);--wnps 不能修改包的变量（不能给包的变量赋值）                                            --wnds 不能执行dml<br />  pragma restrict_references(min_sal,wnps);--rnps 用于限制函数不能读取包变量<br />  end;<img src ="http://www.blogjava.net/kevinfriend/aggbug/74562.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:46 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74562.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>including Constraints</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74561.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:45:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74561.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74561.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74561.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74561.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74561.html</trackback:ping><description><![CDATA[1 What are Constrains<br />  1) Constrains enforce on the table level<br />  2) Constrains the deletion of a table if there are dependencies<br />2 Constrain Guidelines<br />  1) Name a constraint or the oracle generate a name by the sys_cn format<br />  2) Create a constraint either<br />     --At the same time as the table is created.or<br />     --After the table has been created<br />  3)Define a constraint at the column or table level<br />  4)view constraint in the data dictionary<br />3 Crete a constraint<br />  create table test2<br />  (id int not null,-- column level<br />   lname varchar(20),<br />   fname varchar(20),<br />   constraint uk_test2_1 unique(lname,fname))--table level<br />4 The not null Constraint<br />  create table employees(<br />   employee_id number(6),<br />   last_name   varchar2(25) not null  --system named<br />   hire_date   DATE<br />               constraint emp_hire_date not null --User named<br />5Foreign key<br />  create table test3<br />  (rid int,<br />   name varchar(30),<br />   constraint fk_test3_1 foreign key(rid) reference test2(id));<br />  froeign key constraint keywords<br />    foreign key :Define the column in thee child table at the table constrain level.<br />    references  :Identifies the table and column in the parent table.<br />    on delete cascade: Delete the dependent rows in the child table when a row in the     parent table is deleted<br />    on delete set null:Convert the dependent foreign key values to null when a row in the <br />    parent table is deleted.<br />   <br />    --parent table referenced table<br />    --child table refernce other table<br />6 The check Constraint<br />  Define a condition that each row must be satisfy<br />  alter table test3<br />  add constrain ch_test3 check(name like 's%') <br />7 Dropping a Constraint<br />  1) Remove the manager constraint form the employee table<br />   alter table test3<br />   drop constriant test3_manager_fk<br />  2) Remove the primary key constraint on the departments table and drop the associated<br />   foreign key constraint on the employees.department_id column<br />   alter table departments<br />   drop primary key cascade<br />8 Disabling and enable Constraints<br />  1)Execute the disable clause of the alter table statment to deactive an integrity constraint<br />  2)Apply the cascade option to disable dependent integrity constrints<br />  alter table employees<br />  disable constraint emp_emp_id_pl cascade<br />  3) enabling Constraints<br />  .Active an integrity constraint currently disabled in the table definition by using the enable clause.<br />   alter table employees<br />   enable constraint emp_emp_id_pk;<br />  a unique  or a primary  index is automatically created if you enable a unique key or a primary key constraint  <br /> 8 View Constraints<br />  select constraint_name,constriant_type,serch_condition <br />  from user_constraints<br />  where table_name='employees'<br /> 9 view the columns associated with constraints<br /> select constraint_name,column_name<br /> from user_cons_columns<br /> where table_name='employees'<img src ="http://www.blogjava.net/kevinfriend/aggbug/74561.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:45 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74561.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>create view</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74560.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:45:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74560.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74560.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74560.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74560.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74560.html</trackback:ping><description><![CDATA[1Why Use Views<br />  to restrict data access<br />  to make complex query easy<br />  to provide data independence<br />  to provide defferent view of the same data<br />2 Creating a View<br />  1)create [or replace] [force|noforce] view view<br />  as subquery<br />  force : create view wether the referenced object existed or not<br />  <br />  desc view_name;<br /> 2)create a view by using column aliases in the subquery<br />  create view salv50<br />  as select employee_idIO_NUMBER,last_name NAME,slaary*12 ANN_SALARY<br />  from employees<br />  where department_id=50;<br />3 Modigy a View<br />  1) Modigy the emplvu80 view by using create or replace view clause.Add an alias for each column name;<br />   create or replace view empvu80<br />   (id_number,name,sal,department_id)<br />   as select employee_id,first_name||" "||last_name,salary.department_id<br />   from employees<br />   where department_id=80;<br />   column aliases in the create view clause are listed in the same order as the columns in the subquery<br />   note : alter view_name is not a valid command.<br />4 Create a Complex View<br />  Create a complex view that contains group functions to display values from two tables<br />  create view dept_sum_vu<br />   (name,minsal,maxsal,avgsal)<br />  as <br />   select d.department_name,min(e.salary),max(e.salary),avg(e.salary)<br />   from employees e,departments d<br />   where e.department_id=d.department_id<br />   group by d.department_name;<br />5 Rules for performs DML operaton on a view<br />  1) You can perform DML operation on simple views<br />  2) You can not romove a row if the view contains the following:<br />    --group functions<br />    --a group by clause<br />    --the distinct keyword<br />    -- rownum keyword<br />    -- column defined by expressions<br />6 Using the with check option Clause<br />  1) you can ensure that dml operatons performed on the view stay within the domain of the view by using the with check option clause.<br />  create view test1 <br />  as<br />  select * from emp where qty&gt;10;<br />  with check option;<br />  update testview1 set qty=10 <br />  where ster_id=6830;<br />  --when you doing the following update operation<br />  update testview1 set qty=5 where id=10;<br />  -- an error will report<br />  --you violate the where clause<br />  2)Any attempt to change the department number for any row in the view fails because it violates the with check option constraint<br />   create or replace view empvu20<br />   as <br />   select * where department_id=20<br />   with check option constriant empvu20_ck; <br />7 Denying DML Operations<br />  1 You can ensure that no dml operations occur by adding the with read only option to your view definition.<br />  2)Any attempt to a DML on any row in the view resuls in an oralce server error.<br />8 remove veiw<br />  drop view_name<br />9 inline view<br />  1) an inline view is a subquery with an alias that you can use within a sql statement.<br />  2) a named subquery in the from clause of the main query is an exqmple of an inline view<br />  3) an inline view is not a schema object.<br />10 Top-N Analysis<br /> 1)Top_N querise ask for the n largest or smallest values of a column.<br /> 2)Both largest values and smallest values sets considered Top-N queries<br />  select * from (select ster_id,qty from sales);<br /> example<br />  To display the top three earner names and salaries from the employees<br />  select rownum as rank,last_name,salary<br />  from (select last_anme,slary from employee<br />        order by slary desc)<br />  where rownum&lt;=3;<br />  <img src ="http://www.blogjava.net/kevinfriend/aggbug/74560.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:45 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74560.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用触发器</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74559.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:44:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74559.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74559.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74559.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74559.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74559.html</trackback:ping><description><![CDATA[
		<p>1 触发器简介<br />  1) 触发事件<br />  2) 触发条件<br />  3) 触发操作<br />     . 触发器代码的大小不能超过32k，如果使用大量代码建立触发器，应该先建立存储过程，然后再触发器中使用call语句调用存储过程。<br />     . 触发器中正能含有select ，insert，update 和delete 语句，而不能含有ddl 语句，和事物控制语句。<br />2 建立dml 触发器<br /> 1) 触发时机<br />  before，after 表示在执行dml操作之后触发器<br /> 2)触发事件<br />  insert ，update 和delete 操作。也可以使用书法事件<br /> 3) dml 触发器是针对特定表进行的 因此必须制定dml 操作所对应的表<br /> 4) 触发器类型 用于指定当触发器事件之后，需要执行几次触发器操作。如果指定语句触发器类型<br />那么会执行一次触发器代码：如果指定行触发器类型，则会在每个被作用行上执行一次触发器代码。<br /> 5) 触发条件<br /> 用于指定执行行触发器代码的条件，只有为ture时，才会执行行触发器代码。<br />  6) 如果使用pl/sql 存储过程，java 存储过程，或外部处处过程需要在触发器操作部分直接使用call<br />  7) dml 触发器触发顺序<br />   (1)dml 触发器在单行数据上的触发顺序。<br />    对于单行数据而言，无论是语句此触发器，还是行触发器，触发器代码实际只执行一次，并且执行<br />顺序为before 语句触发器，before 行触发器，dml 操作，after 行触发器，after 语句触发器<br />   (2) dml 触发器在多行数据上的触发顺序<br />    before 语句触发器 <br />    before 行触发器<br />    after 行触发器<br />    before行触发器<br />    after 行触发器<br />    after语句触发器<br />   语句触发器只被执行一次，而行触发器在每个行上都执行一次。<br />  2) 语句触发器<br />  当审计dml 操作，或确保dml操作安全执行时，可以使用语句触发器<br />  1 建立before 语句触发器<br />   create or replace trigger tr_sec_emp<br />   before insert or update or delete on emp<br />   begin<br />     if to_char(sysdate,'DY','nls_dtate_language=AMERICAN') in ('sat','sun') then<br />     railse_application_error(-200001,'不能在休息日改变雇员信息');<br />     end if;<br />   end; <br />   2 使用条件谓词<br />   inserting ,updating ,deleting<br />   create or replace trigger tr_sec_emp<br />   before insert or update or delete on emp<br />   begin<br />     if to_char(sysdate,'DY','nls_date_language=american')<br />      in('sat','sun') then<br />     case<br />       when inserting then<br />         raise_application('-20001','inserting');<br />       when updating then<br />         raise_application('-20002','updating');<br />       when deleting then<br />         raise_application('-20003','deleting');<br />     end case;<br />    end if;<br />   end;<br />   3 建立after 语句触发器<br />    为了dml 操作，或者dml 操作后执行汇总运算<br />   create table aduit_table(<br />     name varchar2(20),ins int,upd int,del int,<br />     starttime date,endtime date<br />   );<br />   create or replace trigger tr_aduit_emp<br />   after insert or update or delete emp<br />   declare<br />     v_temp int;<br />   begin<br />     select count(*) into v_temp from aduit_table<br />       where name='emp';<br />     if v_temp=0 then<br />       insert into audit_table values<br />       ('emp',0,0,0,sysdate,null);<br />     end if;<br />     case<br />       when  inserting then<br />         update aduit_table set ins=ins+1,endtime=sysdate where name='emp';<br />       when updating then<br />         update audit_table set upd=upd+1,endtime=sysdate where name='emp';<br />       when deleting then<br />         update aduit_table set del=del+1,endtime=sysdate where name='emp';<br />   end;<br />  3) 行触发器<br />   审计数据变化可以使用行触发器<br />   1 建立不before 行触发器<br />    为了取保数据符合商业逻辑或企业规则，对输入的数据进行复杂的约束，可以使用before行触发器<br />     create or replace trigger tr_emp_sal<br />     before update of sal on emp<br />     for each row<br />     begin<br />       if :new.sal&lt;:old.sla then<br />         raisse_application_error(-200010,'工资只涨不降');<br />       end if；<br />     end;<br />     2) 建立after 行触发器<br />     为了审计dml 操作，可以使用语句触发器或oracle 系统提供的审计功能，而为了审计数据变化<br />，则应该使用after 行触发器<br />     create table audit_emp_change(<br />       name varchar2(10),odl number(6,2),<br />       newsal number(6,2),time date);<br />    create or replace trigger tr_sal_change<br />    after update of sal on emp<br />    for each row<br />    declare<br />     v_temp int;<br />    begin<br />     select count(*) into v_temp from audit_emp_change where name=:old.ename;<br />    if v_temp =0 then<br />      insert into audit_emp_change<br />        values(:old,ename,:old.sal,:new,sal,sysdate);<br />    else<br />      update audit_emp_change <br />        set oldsal=:old.sal,newsal=:new.sal,time=sysdate where name=:old.ename; <br />    end if;</p>
		<p>    end;<br />     )<br />    3) 限制行触发器<br />    当使用行触发器，默认情况下会咱每个被作用行上七星一次触发器代码，为了时得再特定条件下执行行触发器代码，需要使用when 子句<br />    create or replace trigger tr_sal_change<br />    after update of sal on emp<br />    for each row<br />    when(old.job='salesman')<br />    declare<br />       v_temp int..<br />2 dml 触发器使用注意事项<br />  触发器代码不能从触发器所对应的基表中读取数据<br />3 dml 触发器<br />  为了保证数据库满足特定的商业规则或企业逻辑，可以使用约束，触发器和子程序。约束性能最好，实现最简单，所以为售选，如果触发器不盟实现，可以选择触发器。<br />  dml 触发器可以用于实现数据安全保护，数据审计，数据完整性，参照完整性，数据复制等功能。<br /> 1) 控制数据安全<br />  create or replace trigger tr_emp_time<br />  before insert or update or delete on emp<br />  begin<br />    if to_char(sysdate,'hh24') not between '9' and '17' then<br />      raise_application_error(-20101,'not work time');<br />     end if;<br />  end;<br />  2) 实现数据审计<br />  使用数据审计只能审计sql 操作，而不会记载数据变化<br />  audit insert,update,delete on emp by access<br />  3)实现数据完整性<br />  首选约束 alter table emp add constraint ck_sal check (sal&gt;=800),但是在有些情况下只能使用触发器来实现数据完整性<br />   create or replace trigger tr_check sal<br />   before update of sal on emp<br />   for each row<br />   when (new.sla&lt;old.sal or new.sal&gt;1.2* old.sal)<br />   begin<br />      raise_application_error(,,,,,,)<br />   end;<br />  3) 使用引用完整性<br />  采用 on delete cascade 可以进行集联删除，但是却不能进行集联更新。采用触发器实现集联更新<br />   create or replace trigger tr_update<br />   after update of sal on emp<br />   for each row<br />   begin<br />     update emp set depno=:new.deptno where dentno=:old.deptno;<br />   end; <br />4 建立instead of 触发器<br />  对于简单视图可以直接进行insert update 和delete 等操作，但是对于复杂视图不允许进行insert，update 和delete 操作。<br />  满足一下条件的为复杂视图<br />    具有操作集合符 union，union all ，intersect，minus<br />    具有分组函数 min，max，avg，sum，count<br />    具有group by connect 编译 或start with<br />    具有distinct <br />    具有连接<br />  为了在复杂视图上执行dml 操作，必须要基于instead-of 触发器，建立instead－of 触发器后，就可以基于复杂视图执行insert，update和delete 语句。<br />   instead of 选项只使用于视图<br />   基于视图建立触发器时，不能定义before 和 after<br />   在建立视图时不能指定 with check option <br />   当建立instead of 触发器时，必须指定for each row 选项<br />  1) 建立复杂视图dept_emp<br />   create or replace view dept_emp as<br />   select a.deptno,a.dname,b,empno,b,ename<br />   from dept a,emp b<br />   where a,deptno=b.deptno;<br />  2) 建立 instead－of 触发器<br />   create of replacee trigger tr_instead_of_dept_emp<br />   instead of insert on dept_emp<br />   for each row<br />   declare<br />     v_temp int;<br />   beegin<br />      select count(*) into v_temp from dept where deptno=:new.deptno;<br />      if v_temp=0 then<br />        insert into dept(deptno,dname) values(:new.deptno,:new.dname);<br />      end if;<br />      select count(*)into v_temp from emp where empno=:new.empno;<br />      if v_temp=0 then<br />         insert into emp(empno,ename,deptno)<br />           values(:new.deptno,:new.ename,:new.deptno);<br />         end if;<br />   end;<br />   <br />   可以对视图执行insert 操作了<br />    insert into dept_emp values(50,'admin','1223','mary')<br />5 管理触发器<br />  1) 显示触发器信息<br />    select trigger_name,status from user_triggers<br />    where table_name='emp';<br />   2)禁止触发器<br />    alter trigger tr_check_sal disable;<br />   3) 激活触发器<br />    alter trigger tr_check_sal enable;<br />   4) 禁止或激活表上的所有触发器<br />    alter table emp disable all triggers;<br />    alter table emo eanble all triggers; <br />   5)重新编译触发器<br />    alter trigger tr_check_sal compile;<br />   6) 删除触发器<br />    drop trigger tr_check_sal;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74559.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:44 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74559.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用复合变量</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74557.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:44:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74557.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74557.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74557.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74557.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74557.html</trackback:ping><description><![CDATA[1 pl/sql 集合 处理单列多行数据库，使用的类型为标量类型<br /> 1）索引表<br />  type ename_table_type is table of emp.ename%type<br />    index by binary_integer;<br />  ename_table ename_table_type;<br />  begin<br />    select ename into ename_table(-1) from emp <br />      where empno=&amp;no;<br />    dbms_output.put_line('雇员名：'||ename_table(-1));<br />  end;<br />  <br />   set serveroutput no<br />   declare<br />     type area_table_type is table of number<br />        index by varchar2(10);<br />     rea_table area_table_type;<br />    begin<br />        area_table('beijing'):=1;<br />        area_table('shanghai'):=2;<br />        area_table('guangzhou'):=3;<br />        dbms_output.put_line(area_table.first);<br />        dbms_output.put_line(area_table.last);<br />    end;<br />     2) 嵌套表<br />      索引表类型不能作为累得数据类型使用，但是嵌套表可以作为表类的数据类型使用。<br />当使用嵌套表元素时，必须先用其构造方法初始化其嵌套表：<br />       a  在pl/sql 块中使用嵌套表<br />        declare <br />          type ename_table_type is table of emp.ename%type;<br />          ename_table ename_table_type;<br />        begin <br />           ename_table:=eanme_table_type('2','2','3');<br />           select ename into ename table(2) from emp where empno=&amp;no;<br />           dbms_ouput.put_line(ename_table(2));<br />        end;<br />      b 在表中使用嵌套表<br />        create type phone_type is table of varchar2(20);<br />        create table employee(<br />          id number (4),name varchar2(10),sal number(6,2),<br />          phone phone_type <br />        )nested table phone store as phone_table;<br />       -- 为嵌套表插入数据<br />        insert into employee values(2,'scott',200,phone_type('2222','333333'));<br />       －－检索嵌套表累得数据<br />        set serveroutput on<br />        declare<br />          phone_table phone_type;<br />        begin<br />          select phone into phone_table<br />          from employee where id=1;<br />          for i in 1..phone_table.count loop<br />            dbms_output.put_line(phone_table(i));<br />          end loop;<br />        end;<br />       -- 更新嵌套表列的数据<br />         delcare <br />            phone_table phone_type:=('44444','555555');<br />         begin<br />            update employee set phone=phone_table<br />            where id=1;<br />         end;<br />    3) 变长数组<br />      在使用varray 时必须指定最大个数，和数据类型,在使用其元素时必须进行初始化<br />      type ename_table_type is varray(20) of emp.ename%type;<br />      ename_table ename_table_type:=ename_table_type('1','2');<br />      <br />      -- 在快中使用varray <br />      declare <br />         type ename_table_type is varray(20) of emp.ename％type；<br />         ename_table ename_table_type:=ename_table_type('mary');<br />         begin<br />            select ename into ename_table(1) form emp<br />               where empno=&amp;no;<br />          end; <br />      --在表列中使用varray<br />       create type phone type is varray(20) of varchar2(20);<br />       create table employee(<br />         id number(4),name varchar2(10),<br />         sal number(6,2),phone phone_type);<br />       <br />     3)记录表<br />      记录表结合了记录和集合的优点<br />        declare <br />          type emp_table_type is table of emp%rowtype<br />          index by binary_integer;<br />        emp_table emp_table_type;<br />        begin<br />          select * from into emp_table(1) from emp<br />          where empno=&amp;no;<br />          dbms_output.put_line(emp_table(1).ename);<br />        end;<br />      4)多维集合<br />       1 多级varray<br />       declare<br />        --define 一维集合<br />          type al_array_type is varray(10) of int;<br />        --定义二维集合<br />          type nal_varray_type is varray(10) of a1_varray_type;<br />        --初始化二维集合<br />          nvl nal_varray_type:=nal_varray_type(<br />             a1_varray_type(1,2),<br />            a1_varray_type(2,3)<br />          )<br />         beign<br />           for i in 1..nal_varray_type.count loop<br />              for j in 1..a1_array_type.count loop<br />                dbms_out.putline(nvl(i)(j));<br />              end loop;<br />           end loop;<br />        end;<br />       2 使用多级嵌套表<br />        table a1_table_type is table of int;<br />        table nvl_table_type is table of a1_table_type;<br />        nvl nvl_table_type:=nvl_table_type(<br />          a1_table_type(1,2),<br />          a1_table_type(2,3)<br />        );<br />2 集合方法<br />  1) exist<br />   if ename_table.exists(1) then<br />    ename_table(1):='scott';<br />   2) count 返回当前集合变量中的元素总个数<br />    ename_table.count<br />   3) limit 返回集合元素的最大个数  只有varray 有<br />   4)first and last <br />       ename_table.first<br />       ename_table.last<br />   5) prior 和next<br />    ename_table.prior(5); －－返回元素5的前一个<br />    ename_table.next(5);  --  后一个<br />   6) extend<br />    使用于varray 和 嵌套表。<br />    extend add a null value<br />    extend (n) add n null value<br />    extend (n,i)add n i value<br />    declare<br />      type ename_table_type is varray(20) of varchar2(20);<br />      ename_table ename_table_type;<br />    begin<br />      ename_table:=ename_table_type('mary');<br />      ename_table.extend(5,1);<br />      dbms_output.put_line(ename_table.count);<br />    end;<br />   7) trim<br />   trim remove one element from the tail of the collection.<br />   trim(n) remove n element from the tail of the colleciton.<br />   8)delete<br />    delete: delete all the elements<br />    delete(n) :delete the nth elements<br />    delete(m,n): delete the elements from m to n <br />3 集合赋值<br />  1)将一个集合的数据赋值给另一个集合.clear the destination collectins and set the original collection <br />   delcare<br />    type name_varray_type is varray(4) of varchar2(10);<br />    name_array1 name_varray_type;<br />    name_array2 name_varray_type;<br />   begin<br />     name_array1:=name_varray_type('scott','smith');<br />     name_array2:=name_array_type('a','b','c');<br />     name_array1:=name_array2;   <br />   end; <br />   <br />  <br />  type name_array1_type is varray(4) of varchar2(10);<br />  type name_array2_type is varray(4) of varchar2(10);<br />  name_array1 name_array1_type;<br />  name_array2 name_array2_type;<br />  具有相同的数据类型，单具有不同的集合类型不能构赋值<br />  2) 给集合赋城null 值<br />    可以使用delete 或 trim <br />    也可以使用 空集合赋给目表集合<br />    type name_varray_type is varray(4) of varchar2(10);<br />    name_array name_varray_type;<br />    name_empty name_varray_type;<br />    <br />    name_array:=name_varray_type('1','2');<br />    name_array:=name_empty;<br />  3) 使用集合操作赋和比较集合都是10g 的内容，p176 先略过。<br />4 批量绑定<br />  执行单词sql 操作能传递所有集合元素的数据。<br />  1 forall 语句<br />  用于insert update 和delete操作。在oracle9i 中forall 语句必须具有连续的元素<br />    1) using forall on insert<br />     declare<br />        type id_table_type is table of number(6)<br />        index by binary_integer;<br />        type name_table_type is table of varchar2(2)<br />        index by binary integer;<br />        id_table id_table_type;<br />        name_table name_table_type;<br />      begin<br />         for i in 1..10 loop<br />           id_table(i):=i;<br />           name_table(i):='Name'||to_char(i);<br />         end loop;<br />         forall i in 1..id_table.count<br />           insert into demo values(id_table(i),name_table(i));<br />      end;<br />     2)using forall on using update<br />       forall i in 1..id_table.count<br />           upate demo set name:=name_table(i)<br />              where id:=id_table(i);<br />     3)using forall on using delete<br />        forall i in 1..id_table.count<br />            delete from demo where id:=id_table(i);<br />     4) using forall on part of the collection<br />        for i in1..10 loop<br />          id_table(i):=i;<br />          name_table(i):="name"||to_char(i);<br />        end loop;<br />        forall i in 8..10 l<br />           insert into demo values(id_table(i),name_table(i));<br />   2 bulk collect<br />     is fit for select into ,fetch into and dml clause <br />     1) using bulk collect<br />      declares   <br />        type emp_table_type is table of emp%rowtype<br />         index by binary_integer;<br />        emp_table emp_table_type;<br />      begin<br />         select * bulk collect into emp_table<br />          from emp where deptno=&amp;no;<br />         for i in 1..emp_tablee.count loop<br />            dbms_output.put_line(emp_table(i).ename);<br />         end loop;<br />      2) 在dml 的返回字句使用bulk collect 字句<br />         declare <br />          type ename_table_type is table of emp.ename%type;<br />           ename_table ename_table_type;<br />          begin<br />             deletee from emp where deptno=&amp;no<br />             returning ename bulk_collect into ename_table;<br />          for i in 1..ename_table.count loop<br />            dbms_output.put(ename_table(i));<br />          end loop;<br />        end;<br />          end;<br />      end;<img src ="http://www.blogjava.net/kevinfriend/aggbug/74557.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:44 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74557.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>advanced subquery</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74556.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:43:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74556.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74556.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74556.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74556.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74556.html</trackback:ping><description><![CDATA[1 subquery: is a select statement embedded in other sql statement.<br />  .the subquery execute (inner query) once before the main query<br />  .the result of the subquery is used by the main query.<br />2 pairwise comarison subquery<br /> select * from employee<br /> where (manager_id,department_id) in<br />          (select manager_id,department_id<br />           from employees<br />           where employee_id in (178,174))<br /> and employee_id not in (178,174);<br /> nonpairwise comparison subquery<br /> select employee_id,manager_id,department_id<br /> from employee<br /> where manager_id in<br />                  (select manager_id<br />                   from employees<br />                   where employee id in (174,141))<br /> and department_id in<br />                   (select department_id<br />                    from employees<br />                    where employee_id in (174,141))<br /> and employ_id not in (174,141);<br />                  )<br />3 using a subquery in the from clause<br />  select a.last_name,a,salary,b.slaavg<br />  from employees a ,(select department_id,<br />                      avg(salary) salavg<br />                      from   employees<br />                      group by department_id) b<br />   where a.department_id=b.department_id<br />   and a.salary&gt;b.salavg;<br />4 scalar subquery expressions<br />  . a scalar subquery expression is a subquery that return exactly on column value from one row<br />  . in oracle8i scalar subqueries can be used in condition and expression part and all clause.<br /> 1) sclaar subqueries in casse expression<br />   select employee_id ,last_name,<br />   (case<br />    when department_id=<br />          (select department_id from departments <br />          where location_id=1800)<br />    then 'canada'<br />    else 'usa'<br />   end) location<br /> from employees<br />   2)scalar subqueries in order by clasue<br />   select employee_id,last_name<br />   from employees e<br />   order by (select department_name<br />             from departments d<br />             where e.department_id=d.department);<br />4 correlated subqueries<br />   the wubquery references a column form a table in the parment query<br />   select column1,solumn2....<br />   from table1 outer<br />   where column1 operator<br />                         (select column1,column2<br />                          from table2<br />                          where expr1=out.expr2);<br />  e.g 1<br />   select last_name,salary,department_id<br />   from employees outer<br />   where salary&gt;<br />               (select avg(salary)<br />                from employees<br />                where department_id=<br />                   outer.department_id);<br />               )<br />   e.g 2<br />    display details of those employees who have switched jobs at lease twice<br />    select e.employee_id,last_name,e.job_id<br />    from employees e<br />    where 2&lt;=(select count(*)<br />              from job_history<br />              where employee_id=e.employee_id);<br />6 using the exists operator<br />  . the exists operator tests for existencee of rows in the results set of the subquery<br />  . if a subquery row value id found:<br />     the search does not continue in the inner query<br />     the condition is flagged true<br />  .if a subquery row value is not fount<br />     the condition is flagged fasle<br />     the search continues in the inner query<br /> e.g<br />    find employees who have at least one person reporting to them<br />    select employee_id,last_name,job_id,department_id <br />    from employees outer<br />    where exists (select count(*)<br />                 from employees<br />                 where manager_id=outer.employee_id);<br />  not exist.<br />7 corelated update<br />    use a correlated subquery to update rows in on table based on rows from another table<br />   e.g<br />    --denormalize the employees table by adding a column to store the department name<br />    alter table employees<br />    add(department_name varchar2(14));<br />   --populate the table by using a correlated update<br />    update employees e<br />    set department_name=<br />                       (select department_name<br />                        from departments d<br />                        where e.departmentid=d.department);<br />8 correlated delete<br />    delete test1 t1<br />    where ster_id in(select ster_id form sales t2 where t.ster_id=t2.ster_id); <br />9 using the with clause ,you can use the same query block in a a select statement when it cocurs more than once within a complex query<br />  the with clause retrieves the results of a query block and stores it in the user's the user's templary tablespace<br />  the with clause improves performance.<br /> e.g<br />   with <br />   dept_costs as(<br />    select d.department_name,sum(e.salary) as dept_total<br />    from employee e,departments d<br />    where e,department_id=d.department_id<br />    group by d.department_name),<br />   avg_cost as(<br />     select sum(dept_total)/count(*) as dept_avg<br />     from dept_cost)<br />  select * <br />  from dept_costs<br />  where dept_total&gt;(select dept_avg<br />                    from afb_cost)<br />  order by department_name; <img src ="http://www.blogjava.net/kevinfriend/aggbug/74556.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/kevinfriend/" target="_blank">康文</a> 2006-10-11 14:43 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74556.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>