﻿<?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-kevin-随笔分类-数据库</title><link>http://www.blogjava.net/kevinfriend/category/12777.html</link><description /><language>zh-cn</language><lastBuildDate>Fri, 02 Mar 2007 06:56:21 GMT</lastBuildDate><pubDate>Fri, 02 Mar 2007 06:56:21 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>开发子过程</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>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/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>处理例外</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>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>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>使用复合变量</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>使用触发器</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>开发动态sql</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74555.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/74555.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74555.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74555.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74555.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74555.html</trackback:ping><description><![CDATA[
		<p>1 动态sql 简介<br />2 <br />  1 使用execute immediate 处理ddl 操作<br />    create or replacee procedure drop_table(table_name varchar2)<br />    is<br />     sql_statement varchar2(100);<br />    begin<br />       sql_statement:='drop table'||table_name;<br />       execute immediate sql_statement;<br />   调用<br />       exec drop_table('worker');<br />    end;<br />    2) 使用 execute immediate 处理dcl 操作<br />    create or replace procedure grant_sys_priv<br />    (priv varchar2,username varchar2)<br />    is<br />    begin <br />     sql_stat:='gruant'||priv||'to'||username;<br />     execute immediate sql_stat;<br />    end;</p>
		<p>   exec grant_sys_priv('create session','scott');<br />   3 使用execute immediate 处理dml 操作<br />     1) 处理无占位符和returning 子句的dml 语句<br />     delcare<br />      sql_stat varchar2(100);<br />     begin<br />      sql_stat:='update emp set sal=sal*1.1 where deptno=44';<br />      execute immediate sql_stat;<br />     end;<br />      2) 处理包含占位符的dml语句<br />       delare <br />        sql_stat varchar2(100);<br />       begin<br />         sql_stat:='update emp set sql=sql*(1+:percent/100)' <br />                 ||'where deptno=:dno';<br />         execute immediate sql_stat using &amp;1,&amp;2;<br />       end;<br />      3) 处理包含returning 子句的dml语句<br />       declare<br />         salary number(6,2);<br />         sql_stat varchar2(200);<br />       begin<br />         sql_stat:='update emp set sal=sal*(1:percent/100)'<br />            ||'where empno=:eno returning sal into :salary';<br />         execute immediate sql_stat using &amp;1,&amp;2;<br />            returning into salary;<br />       end;<br />       输入1的值 15<br />       输入2的值 2222<br />       新工资；2223<br />      4) 使用execute immediate 处理单行查询<br />        declare<br />          sql_stat varcchar2(100);<br />          emp_record emp%rowtype;<br />        begin<br />          sql_stat:='select * from emp where empno=:eno';<br />          execute immediate sql_stat into emp_record using &amp;1;<br />       end;<br /> 3 处理多行查询语句<br />   declare<br />      type empcurtyp is ref cursor;<br />      emp_cv empcurtyp;<br />      emp record emp%rowtype;<br />      sql_stat varchar2(100);<br />   begin<br />      sql_stat:='select * from em where deptno=:dno';<br />      open emp_cv for sql_stat using &amp;dno;<br />      loop<br />         fetch emp_cu into emp_record;<br />         exit when emp_cv%notfound;<br />      end loop;<br />      close emp_cv;<br />   end;<br />4 在动态sql 中使用bulk语句<br />   1) 在 execute immediate 语句中使用动态bulk 语句<br />     declare<br />       type ename_table_type is table of emp.ename%type<br />        index by binary_integer;<br />       type sal_table_type is table of emp.sal%type<br />        index by binary_integer;<br />       ename_table ename_table_type;<br />       sa_table sal_table_type;<br />       sal_stat varchar2(100);<br />       begin<br />         sql_stat:='update emp set sal=sal*(1+:percent/100)'<br />           || 'where deptno=:dno'<br />           ||'returning ename,sal into :name,:salary';<br />       execut immediate sql_stat using &amp;percent,&amp;dno<br />         returning bulk collect into ename_table,sal_table;<br />       for i in 1..ename_table.count loop<br />       ....<br />       end loop;<br />     end;<br />    2) 使用bulk 子句处理多行查询<br />      sql_stat:='select ename from emp where deptno=:dno';<br />      execute immediate sql_stat bulk collect into ename_table using &amp;dno; <br />    3) 在fetch 语句中使用bulk 子句<br />      declare <br />        type empcurtyp is ref cursor;<br />        emp_cv empcurtyp;<br />        type ename_table_type is table of emp.ename%type;<br />         index by binary_integer;<br />        ename_table ename_table_type;<br />        sql_stat varchar2(100);<br />       begin<br />         sql_stat:='select ename from emp where job:=title';<br />         open emp_cv for sql_stat using '&amp;job';<br />         fetch emp_cv bulk collect into ename_table;<br />    4) 在forall 语句中使用bulk 子句<br />      declare<br />        type ename_table_type is table of emp.ename%type;<br />        type sla_table_type is table of emp.sal%type;<br />        ename_table ename_table_type;<br />        sal_table sal_table_type;<br />        sql_stat varchar2(100);<br />      begin<br />        ename_table:=ename_table_type('scott','smith','clark');<br />        sql_stat:='update emp set sal=sal*1.1 where ename=:1'<br />            ||'returning sal into :2';<br />        forall i in 1..ename_table.count<br />          execite immediate sql_stat using ename_table(i)<br />            returning bulk collect into sal_table;        <br />      end;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74555.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/74555.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><item><title>archetecture query</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74553.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:42:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74553.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74553.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74553.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74553.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74553.html</trackback:ping><description><![CDATA[
		<p>1 hierachical Queries<br /> select [level],colun,expr......<br /> from table<br /> [where condition(s)]<br /> [start with condition(s)]<br /> [connect by prior condition(s)]<br /> <br /> where condition<br />  exprcompparison_operator expr</p>
		<p>2 Starting Point<br /> .Specifies the condition that must be met<br /> .Accepts any valid condition<br />3 Waling the Tree<br />  connect by prior column1=column2<br />  walk from the top donw ,using the employees table<br />   top donw<br />     column1=parentkey<br />     column2=childkey<br />   bottom up<br />     column1=child key<br />     column2=parent key</p>
		<p>  select level,last_name <br />  from employees<br />  start with last_name='king'<br />  connect by prior employee_id=manager_id;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74553.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:42 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74553.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>managing an oracle instance</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74554.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:42:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74554.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74554.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74554.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74554.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74554.html</trackback:ping><description><![CDATA[1 <br />  1)system parameter file -- spfile&lt;sid&gt;,spfile (oracle 9i or later) is a binary file ,it cann't been edited by the text editor. you can change it through "alter system XXX";<br />  in oracle 9.2.0,spfile is stored in the directory of ora92\datatase\spfile&lt;sid&gt;.ora.<br />  2)init parameter file(pfile)--init&lt;sid&gt;.ora  (early version) is a text file.it is stored in admin\&lt;sid&gt;\pfile.<br /> 2<br />   Entries are specific to the instance being accessed;<br />   there are two kinds of parameters:<br />      explicit: having an entry in the file<br />      implicit: no entry within the file,but assuming the oracle default values;<br />   Multiple files can be used for a single datasbase to optimize performance in different situation.<br />    static parameter file,pfile (init.ora)<br />    persistent parameter file,spfile(spfile&lt;sid&gt;.ora);<br />3 order being used<br /> first spfile&lt;sid&gt; then int&lt;sid&gt;.ora<br /> select name,value from v$system_parameter<br />4 spfile spfilesid.ora<br />  1)Binary file with the abiility to make changes persistent across shutdown and startup<br />  2)Maintained by oracle server<br />  3)Record parameter value change made with the alter system command<br />  4)Can specify wether the change being made is tempory or persistent<br />  5)value can be delete or reset to allow an instance to revert to the default value;<br />    e.g<br />    alter system set timed_statistics=false scope=memory;<br />   alter system set timed_statistics=false scope=spfile;<br />   startup force-- restart oracle<br />   select name,value from v$system_parameter where name like 'time%';<br />   alter system set timed_statistics=false scope=both;<br />  6) not all entries can be modified.to see more ,you can lool up v$system_parameter.in this table the isses_modifiable and issys_modifiable will tell which one  can be modified in session,and which one can be modified in sys, and which one cann't be modified.<br />   e.g<br />   select name,isses_modifiable from v$system_parameter where isses_modifiable='true';<br />   alter session set timed_statistics=false;<br />   e.g<br />   select name,issys_modifiable from v$system_parameter where issys_modifiable&lt;&gt;'false';<br />   <br />   .issys_modifiable may have two values immediate or deffered.<br />    immediate means alter this entry will take effect on the current session ,while derrered will take effect on a new session.<br /> <br />5 pfile initsid.ora<br />  .the pfile is a text file than can be modigied with an operation system editor.<br />  .modifications to the file are made manually.<br />  .changes to the file take effect on the next startup<br />6 Creating an spfile<br />   spfile can be created from initsid.ora file using thee create spfile command,whick can be executed before or after instance startup.<br />   create spfile from pfile. -- you must shutdown the instance befofe or you can use the fellow statement:<br />    create spfile='d:\oracle\oracle\ora92\database\spfile.ora' from pfile;<br /> yo caan backup the <br />7 Oracle Managed files(OMF)<br />  1) OMF are created and deleted by the oracle server as directed by sql commands<br />  2) OMF are established by parameters:<br />     DB_CREATE_DEST: set to give the default location for data files<br />     DB__CREATE_OMLINE_LOG_DEST_N: set to gieve the default locations for online redo logs and control files,up to a mazimum of 5 locations.<br />    e.g 1<br />    show parameter db_create<br />    e.g 2<br />    create tablespace test1;--report error,Do not konw where create the data file<br />    alter system set db_create_file_dest='d:\oracle\oradb';<br />    create tablespace test1; -- is ok;<br />    e.g 3<br />    alter database add logilfe group 6;<br />    -- if you do not specify the db_create_online_log_dest_N ,the log file will create at     --the location which is specified by the db_create_file_dest.<br />    e.g 4<br />    drop table test1; -- oracle alse remove it's physicial file;<br />    alter database drop logfile group 6-- also romove the physical file.<br />    e.g 5<br />    create tablespace test1<br />    datafile 'd:\oracle\oradb\test1.dbf' size 2m;<br />    drop tablespace test1 -- if you create tablespace or others object in this way ,you                           --will cann't remove the physical file.<br />    drop table test1 including comtents and datafiles;<br />8 Starting up a database mount<br /> startup nomomount :instance started for this instance;create db.create controlfule<br />     1) create alert_sid.log  startup log which is stored in &lt;oracle_home&gt;\admin\&lt;sid&gt;\bdump<br />     2) start instance include allocating memory and start bpprocess<br />    select * from v$instance;<br />    select * from v$bgprocess;<br />    select * from V$sga;<br />  alter database mount; <br />    open control files for the instance;<br />    select* from v$database;<br />    select* from v$tablespace;<br />    select* from datafile;<br />    select* from log;<br /> alter database open;<br />    all files opened as describled by the control file for this instance;<br />9 start up <br />  start pfile=...\initsid.ora;   (alter session set nls_language=american)<br />  alter database open read only; you can not change database to read only after the database has been created.<br />  startup database restrict;<br />  alter system enable restricted session;-- only people with restricted privilege can                                          --access the database;<br />   alter restricted session to kkk;<br />   alter disable restricted session <br />10 opening a database in read only mode<br />   a databse can be opened as read only database alter database open read only;<br />   a read-only database can be used to :<br />     execute queries<br />     execute disk sorts using locally managed<br />     take data files offline and online ,not tableespaces<br />     perform recovery of offline data files and tablespace;<br />11Shutting down teh database<br />  normal: wait until current sessions end,wait until current trasactions end ,force a checkpoint and close files.<br />  tansactional:wail until current transaction end.force a checkpoint and close files<br />  immediate :force a checkpoint and close the files<br />  abort     : do nothing ,just close the files. when startup ,need recovery.<br />12 Managing an instance by monitoring Diagnostic Files<br />  Diagnostic files contain information about significant events encounted while the instance is operational.<br />   .user to resolve problem or to better manager the database.<br />   .server types of dignostic files exist:<br />      alertsid.log  --which location is specified by the background_dump_dest                                   --entry in the initsid.ora.tje default value is                     --&lt;ora_home&gt;\admin\sid\bdump<br />      background trace files -- the same as above;<br />      user_tace files<br />13 alert log file<br />   the alertsid.log file recored the command and result of major event while the database is operational.<br />   .it is userd for day-to-day operational information or dignosing database errors<br />   .ench entry has a time stamp associated with it.<br />   .the dba manager the alertsid.log file.<br />   .its location is defined by background_dump_dest.<br />14 enabling or disabling user tracing<br />    . sessin level using the alter session <br />      alter session set sql_trace=true;<br />    session level by execcuting dbms<br />     <img src ="http://www.blogjava.net/kevinfriend/aggbug/74554.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:42 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74554.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Managing Passswordd Security and Resources</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74551.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:41:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74551.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74551.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74551.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74551.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74551.html</trackback:ping><description><![CDATA[
		<p>1 Profiles<br />  1)a profile is a named set of password and resource limits<br />  2)Profiles are assigned to user by the create user or alter user command<br />  3)can be enable or disable<br />  4)can relate to the default profile.<br />2 Password Management<br />  Password history,account locking,password expiration and aging ,password verificcation.<br />3Enabling Password Management<br />  1)set up passwordd management by using profiles and assign them to users<br />  2)lock unlock and expire accounts usign the create user or alter user<br />  3)alwarys enforcing<br />   e.g<br />   create user test identified by test;<br />   alter user test account lock;<br />   alter user test account unlock;<br />   alteer user test password expire;<br />4 Passowrd Account locking<br />  FAIKED_LOGIN_ATTEMPS: number of failed login attemts before lockout of the account<br />  PASSWORD_LOCK_TIME : number of days the account is locked after the specified number of                        failed login attemps<br />  e.g<br />  create profile profile1 limit<br />  password_lock_time 1/1440  -- one muinuts<br />  failed_login_attempts 3;<br />  <br />  alter user test <br />  profile profile1;</p>
		<p>  alter profile profile1 limit<br />  passowrd_lock_time 1/24  --one hour<br />5 passowrd expiration and aging<br /> passwowd_life_time lifetime of the passowrd in days  after which the password expires(有效期)<br /> password_grace_time grace period in days for changing the password after the first                      successful login afteer the password has expired(锁定期)<br /> e.g<br /> alter profile profile1 limit<br /> password_life_time 2<br /> password_grace_time 3;<br />6 password history<br /> password_reuse_time:number of days before a passowrd and be resued<br /> password _reuse_max:maxum number of times password can bee reused<br /> e.g<br /> alter profile profile1 limit<br /> password_reuse_time 10<br /> password_reuse_max 3;<br />7passowrd Verification(study latter)<br />8drop a profile<br /> drop profile profile1 (cascade);<br />the user will use the default profile.it will take effect on the new session.<br />9 Resource Management<br /> Resource mangement limits can be enforced at the session level,the call level or both<br /> limits can be defined by profiles using the create profile command<br /> enable resource limints with the<br />  .resource_limit initialization parameter<br />   alter system command<br /> e.g<br /> alter system set resource_limit=true;<br />10 setting a Resdource limits at session level<br />  cup_per_session : total cpu time measured in hundredths of seconds (百分之一秒)<br />  sessions_per_user: number of coucurrent sessions allowed for each username<br />  connect_time:elapsed connect time measured in minutes<br />  idle_time :periods of inactive time measured in minutes<br />  logical_reads_per_session: number of data blocks<br />  private_sga :measure in reads<br />  e.g<br />  alter profile profile1 limit<br />  cpu_per_session 100000<br />  connect_time 60<br />  idle_time 5;<br />  <br />  alter user test profile profile1</p>
		<p>11 Setting Resource limits at call level  <br /> e.g<br /> alter profile profile1<br /> cpu_per_call 1000  -- cup time per call in<br /> logical_reads_per_call --number of data balock that can be read per call<br /> <br />  create profile develper_prof limit<br />   session_per_user2<br />   cpu_per_session 10000<br />   idle_time 60<br />   connect_time 480<br />12 Managing Resources using database resource manager<br />   1)Provides the oracle server with more control over resorce management decisions<br />   2)elements of database resorcee manager<br />    resource consumer group<br />    resourcee plan<br />    resource allocation method<br />    resource plan directives<br />   3)dbms_resource_manager package is uerd to create and maintain elements<br />   4)requires administer_resource_manager privilege<br />    desc dbms_resoource_manager<br />13 0btaining password and resource limits informaiton<br />  information about password and resource limits can be obtained by querying the data dictonary<br />   dba_users<br />   select * from users;<br />   dba_profiles<br />   select * from dba_profiles where profile='PROFILE1'</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/74551.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:41 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74551.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>extension to dml in oracle</title><link>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74552.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 11 Oct 2006 06:41:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74552.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/74552.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/10/11/74552.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/74552.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/74552.html</trackback:ping><description><![CDATA[1 over of multitable insert statements<br /> 1)the insert...select statement can be userd to insert row into multiple table as part of a single dml statement.<br /> 2) multitable insert statements can be used in data warehousing systems to transfer data from one or more operational sources to source to a set of target table.<br /> 3) they providde significant performance improvement over<br />    single dml versuls multiple insert...select statement<br />    single dml versus a proceedduree to do mutiple inserts using if ,,, then syntax.<br />2<br />  unconditional insert<br />  insert all<br />    into sal_history values (EMPID,HIREDATE,SAL)<br />    into mgr_history values (EMPID,MGR,SAL)<br />  select employee_id EMPID,hire_date JIREDATE,<br />         salary SAL,manager_id MGR<br />  from employees<br />  where employee_id&gt;200;<br />3 Conditional insert all<br />  insert all<br />   when sal&gt;1000 then<br />     into sal_history values(empid,hiredate,sal)<br />   when mgr&gt;200 then<br />     into mgr_history values(empid,mgr,sal)<br />   select emp_id empid,hire_date hiredate,salary sal,manager_id mgr,<br />   from employees<br />   where employee_id&gt;200;<br />4 Conditional first insert<br />  insert first<br />    when sal &gt;25000  then<br />      into special_sal values(deptid,sal)<br />    when hiredate like ('%00%') then<br />      into hiredate_history_00 values(deptid,hiredate)<br />    when hiredate like ('%99%') then<br />      insert hiredate_history_99 values(ddeptid,hiredate)<br />    else<br />      into hiredate_history values(deptid,hiredate)<br />    select ddepartmeent_id deptid,sum(salary) sal,<br />     max(hire_date) hiredate<br />    from employees<br />    group by department_id;<br />5 Pivoting insert<br /> insert all<br />  into sales_info values (employee_id,week_id,sales_mon)<br />  into sales_info values (employee_id,week_id,sales_tue)<br />  into sales_info values (employee_id,week_id,sales_wed)<br />  into sales_info values (employee_id,week_id,sales_thur)<br />  into sales_info values (employee_id,week_id,sales_fri)<br />  select employee_id,weekid,sales_mon,sales_tue,sales_wed,sales_thur,sales_fri<br />  from sales_source_data;<br />6 create index with create table statement<br />  create table new_emp<br />  (employee_id number(6)<br />         primary key using index<br />         (create index emp_id_idx on new_emp(employee_id)),<br />   first_name varchar2(20),<br />   last_name varchar2(25)<br />  )<img src ="http://www.blogjava.net/kevinfriend/aggbug/74552.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:41 <a href="http://www.blogjava.net/kevinfriend/archive/2006/10/11/74552.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>access controll </title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72839.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 29 Sep 2006 07:40:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72839.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72839.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72839.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72839.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72839.html</trackback:ping><description><![CDATA[
		<p>1Privilgeges<br /> 1) Database security:<br />  --System security<br />  --Data security<br /> 2)System privileges:Caining access to the database<br /> 3)Object privileges:manipulationg thee content of the database objects<br /> 4)Schemas:Collections of objects ,such as tables,views,and sequences<br />2System Privileges<br />  . More than 100 privileges are available;<br />  . The database administrator has high-levle system privileges for tasks such as:<br />    creating new user,removing user,removing tables,backing up tables<br />3 Creating user<br /> the dba creates users by using the create user statement<br /> create user user<br /> identified by password;<br /> e.g create user object scott<br />     identified by tiger;</p>
		<p> SQL&gt; create user testuser<br />  2  identified by test;</p>
		<p>User created</p>
		<p>SQL&gt; conn <a href="mailto:testuser/test@orcl2000">testuser/test@orcl2000</a><br />Not logged on</p>
		<p>SQL&gt; grant access session to testuser;</p>
		<p>grant access session to testuser</p>
		<p>Not logged on</p>
		<p>SQL&gt; conn <a href="mailto:digit_cc/digit_cc@orcl2000">digit_cc/digit_cc@orcl2000</a><br />Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0 <br />Connected as digit_cc</p>
		<p>SQL&gt; grant create session to testuser;</p>
		<p>Grant succeeded</p>
		<p>SQL&gt; conn <a href="mailto:testuser/test@orcl2000">testuser/test@orcl2000</a>;<br />Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0 <br />Connected as testuser<br />4 user System privileges<br /> once a user is created,the dba can grant specific system privileges to a user<br /> grant privilege[,privilege...]<br /> to user [,user|role,public...];</p>
		<p> DBA can grant a user specific system privileges<br /> grant create session,create table,create sequence,create view  to scott;<br />5 creating and granting privileges to role<br />' Create a role<br />  create role manager;<br /> .grant privileges to a role<br />  grant create table,create view to manager<br /> .Grant a role to user<br />  grant manager to kochar;<br />  <br />SQL&gt; create role testrole;</p>
		<p>Role created</p>
		<p>SQL&gt; grant create table,create view,create sequence to testrole;</p>
		<p>Grant succeeded</p>
		<p>SQL&gt; grant testrole to testuser;<br />6 change your password<br /> you can change your password by using the alter user statement;<br /> alter user scott<br /> indetified by lion;<br />7 object privileges<br /> object privileges vary from object to object<br /> an owner has all the privilege to the object<br /> an owner can give specific privilege on that owner object<br />  grant select on auther to testuser;<br />  grant select on outher to testuser with grant option -- testuser also can grant it to </p>
		<p>other user; <br />  grant update(department_name,location_id)<br />  on departments<br />  to scott,manager;<br />8 how to revoke object privileges<br /> --you use the revoke statement to revoke privileges granted to other users<br /> --privileges granted to other users through the with grant option clause are also revoked.<br />  revoke privilege {[,privilege...]|all} on object<br />  from {user[,user....]|role|public}<br />  [cascade constraints]<br />  revoke select on author from user;<br />9 Database Links<br /> Database link allow user to access data in the remote database;<br />SQL&gt; create database link kjw1<br />  2  connect to digit_cc identified by digit_cc<br />  3  using 'orcl2000';</p>
		<p>Database link created</p>
		<p>SQL&gt; select * from <a href="mailto:digit_cc.table_action@kjw1">digit_cc.table_action@kjw1</a>;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/72839.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-09-29 15:40 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/29/72839.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>database link  使用 转载</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72838.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 29 Sep 2006 07:35:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72838.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72838.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72838.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72838.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72838.html</trackback:ping><description><![CDATA[
		<p>链接到远程数据库 </p>
		<p>在一个分布式的环境里，数据库链接是定义到其它数据库的路径的一个重要方法，使得远程处理天衣无缝。</p>
		<p>要获得数据库链接的更深奥的知识，查看Oracle8i SQL Reference（Oracle8i SQL参考）和Oracle8i Concepts （Oracle8i概念手册）。详细资料的另一个极好的来源是Oracle8i Distributed Database Systems（Oracle8i分布式数据库系统手册）。</p>
		<p>今天许多运行Oracle的机构有不止一个Oracle数据库。有时不管原计划是否这样，一个数据库中的数据可能与另一数据库中的数据关联。出现这种情况时，你可以链接这两个数据库使得用户或应用程序可以访问所有数据，就好象它们在一个数据库中。当你这么做时，你就有了一个分布式数据库系统。 </p>
		<p>如何将两个数据库链接在一起呢？使用一个数据库链接来完成。数据库链接是定义一个数据库到另一个数据库的路径的对象。数据库链接允许你查询远程表及执行远程程序。在任何分布式环境里，数据库链接都是必要的。 </p>
		<p>简单案例</p>
		<p>数据库链接的目的是定义一条到远程数据库的路径，使你可以通过在本地执行一条SQL语句来使用那个数据库中的表和其它的对象。例如，你在一个远程数据库上有一个称之为"geographic feature name"的表，而你想在已连接到你本地数据库的情况下访问那些数据。数据库链接正是你所需要的。在建立它之前，你必须搜集如下信息： </p>
		<p>一个网络服务名称，你的本地数据库事例能够使用它来与远程事例相连接远程数据库上的有效用户名和口令网络服务名称是每一个数据库链接必需的。每一次你从客户机PC使用SQL*Plus连接到你的数据库时都要使用服务名称。在那些情况下，你提供给SQL*Plus的网络服务名称是通过在你的客户机上的nsnames.ora文件中查找它们来解析的。在数据库链接中使用的网络服务名称也是如此，除非是那些名字是使用驻留在服务器上的tnsnames.ora文件来解析。 </p>
		<p>在你定义数据库链接时指定的用户名和口令，用于建立与远程事例的连接。不需硬编码用户名和口令，建立数据库链接也是可能的甚至是值得选取的。既然这样，现在我们注意这个最直接的例子。 </p>
		<p>下列语句建立了一个数据库链接，它允许访问客户帐户，这个帐户是事先在GNIS数据库建好的：</p>
		<p>CREATE DATABASE LINK GNIS<br />CONNECT TO GUEST IDENTIFIED BY WELCOME<br />USING 'GNIS';</p>
		<p>链接名称GNIS紧随LINK关键字。当连接到远程事例时，CONNECT TO...IDENTIFIED子句指定UEST/WELCOME作为用户名和口令使用 。USING子句指定通过网络服务名称GNIS建立连接。使用这一链接，现在你可以在远程数据库上查询数据。例如：</p>
		<p>SQL&gt; SELECT GFN_FEATURE_NAME<br />2 FROM <a href="mailto:GNIS.FEATURE_NAMES@GNIS">GNIS.FEATURE_NAMES@GNIS</a><br />3 WHERE GFN_FEATURE_TYPE='falls'<br />4 AND GFN_STATE_ABBR='MI'<br />5 AND GFN_COUNTY_NAME='Alger';</p>
		<p>GFN_FEATURE_NAME<br />_________________<br />Alger Falls<br />Au Train Falls<br />Chapel Falls<br />Miners Falls<br />Mosquito Falls<br />Tannery Falls<br />..</p>
		<p>在SELECT语句中@GNIS紧随表名称，说明GNIS.FEATURE_NAMES表是在远程数据库，应该通过GNIS链接访问，链接类型Oracle支持几种不同类型的链接。这些类型相互重叠，有时难以通过选项进行分类。当你建立数据库链接时，你需要从下面选取： </p>
		<p>Public（公用）或Private （私有）链接 </p>
		<p>权限类: Fixed User（固定用户）, Connected User（连接用户）或 Current User（当前用户） <br />Shared Link（共享链接）或 Not Shared Link（非共享链接） <br />每次创建数据库链接时，你要自觉不自觉地做这三种选择。 </p>
		<p>
				<br />公用链接与私有链接相对比</p>
		<p>公用数据库链接对所有的数据库用户开放访问权。前面显示的是私有数据库链接，它只对建立它的用户授权。公用数据库链接更为有用，因为它使你不必为每一个潜在用户创建单独的链接。为了建立一个公用数据库链接，使用如下显示的PUBLIC关键字： </p>
		<p>CREATE PUBLIC DATABASE LINK GNIS<br />CONNECT TO GUEST IDENTIFIED BY WELCOME<br />USING 'GNIS';</p>
		<p>即使这是一个公用链接，用户名仍旧固定。所有使用这个链接的用户都作为用户GUEST连接到远程数据库。 </p>
		<p>
				<br />使用数据库链接访问远程表</p>
		<p>图1 数据库链接GNIS，指明网络服务名称，链接PROD事例到GNIS事例中的FEATURE_NAMES表。 </p>
		<p>
				<br />权限类</p>
		<p>当你建立一个数据库链接时，关于你如何授权对远程数据库进行访问，有三种选择。这三种选择代表了数据库链接的另一种分类方法。这三种类别如下： </p>
		<p>固定用户。为远程数据库链接指定用户名和口令，作为数据库链接定义的一部分。 <br />连接用户。在不指定用户名和口令时创建的数据库链接。 <br />当前用户。建立数据库链接并指定CURRENT_USER关键字。 <br />固定用户数据库链接是指在创建链接时为远程数据库指定用户名和口令。这一链接不管什么时候使用，也无论谁使用，都使用相同的用户名和口令登陆到远程数据库。到目前为止你在本文中所看到的都是固定用户链接。 </p>
		<p>固定用户链接，尤其是公用固定用户链接的一个潜在问提是他们把远程系统上的同一帐户给了许多本地用户。从安全角度来说，如果所有的本地用户在远程系统上拥有同一个帐户，责任就要折中，这取决于用户的数量 。如果数据丢失，几乎不可能确定破坏是如何发生的。另一个潜在问题是公用固定用户链接将对远程数据库的访问权给了所有的本地数据库用户。 </p>
		<p>如果你不想在数据库链接中嵌入用户名和口令，Oracle提供给你另一个非常有用的选择。你可以建立一个连接用户链接。连接用户链接是这样的链接，它通过任一个正在使用该链接的本地数据库的用户的用户名和口令登陆到远程数据库。你可以通过简单地空出用户名和口令来建立一个连接用户链接。考虑如下定义： </p>
		<p>CREATE PUBLIC DATABASE LINK GNIS </p>
		<p>USING 'GNIS'; </p>
		<p>链接名是GNIS。它连接到远程数据库连接时使用的网络服务名称是GNIS，但是没有指定用户名和口令。当你在查询中使用这个链接时，它将向远程数据库发送你当前的用户名和口令。例如，如果你使用AHMAD/SECRET 登陆到你的本地数据库，那么AHMAD/SECRET将是你登陆到远程数据库时使用的用户名和口令。 </p>
		<p>为了使用一个连接用户链接，你必须在远程数据库上有一个帐号，了解这一点是很重要的。不但这样，而且你在两个数据库上应使用同样的用户和口令。如果本地登陆使用AHMAD/SECRET，那么登陆到远程数据库时也必须使用同样的用户名和口令。使用连接用户链接时，如果你的口令不同，你就无权登陆。 </p>
		<p>公用连接用户数据库链接尤其有用，因为你可以建立一个可被所有用户访问的链接，并且所有用户被分别使用他或她自己的用户名和口令授权。你获得责任方面的利益，没有将远程数据库向你的本地数据库上的每一位用户开放。代价是你必须在两个数据库上建立用户帐户，并且你必需确信口令保持一致。 </p>
		<p>当前用户链接通过使用CURRENT_USER关键字建立并且与连接用户链接相似。只有当使用Oracle Advanced Security Option（Oracle高级安全选项）时，你才能使用当前用户链接，这个链接只对授权使用X.509认证的用户有用。 </p>
		<p>
				<br />共享链接</p>
		<p>共享数据库链接是指该链接的多个用户可以共享同一个底层网络连接。例如，在有四位用户的MTS（多线程服务器）环境下，每一个共享服务器进程都将与远程服务器有一个物理链接，这四位用户共享这两个链接。 <br />表面上，共享链接乍一听起来像是一件好事。在某些环境下的确如此，但是，当你考虑使用共享链接时，应当意识到这有许多局限性和警告： </p>
		<p>
				<br />如果你使用一个专用的服务器连接来连接到你的本地数据库，链接只能在你从那些连接中创建的多重会话间共享。 在MTS环境里，每一个共享服务器进程潜在地打开一个链接。所有的会话被同一共享服务器进程提供并且分享被那个进程打开的任意共享链接。因为在MTS环境里的一个共享服务器进程能够服务于许多用户连接，共享链接的使用可能导致打开的链接远多于所必须的链接。用SHARED关键字建立共享数据库链接。还必须使用AUTHENTICATED BY 子句在远程系统上指定一有效的用户名和口令。如下命令建立一个共享的、公用的、连接用户数据库链接： </p>
		<p>
				<br />CREATE SHARED PUBLIC DATABASE LINK GNIS<br />AUTHENTICATED BY DUMMY_USER IDENTIFIED BY SECRET<br />USING 'GNIS';</p>
		<p>要获得创建链接和管理分布式系统的更多资料，请查阅Oracle Technology Network (<a href="http://otn.oracle.com/">http://otn.oracle.com/</a>)。 <br />使用AUTHENTICATED BY子句稍微有些困扰，但是由于实现共享链接的方式安全性决定它是必须的。这个例子中的用户名和口令DUMMY_USER/SECRET必须在远程系统上有效。然而，远程系统上使用的帐户仍就是连接用户的帐户。如果我以JEFF/SECRET登陆到我的本地数据库并使用我刚建好的共享链接，将会发生以下一系列事件： </p>
		<p>
				<br />为了打开链接，Oracle使用DUMMY_USER/SECRET向远程数据库授权。 然后，Oracle试图使用HMAD/SECRET使我登陆到远程数据库。共享链接的主要目的是减少两个数据库服务器之间的底层网络连接数量。它们最适合于MTS环境，在那你拥有大量的通过这一链接访问远程数据库的用户。观念上，你想让用户数量超过共享服务器进程的数量。那么你可以通过为每一共享服务器进程打开一个链接而不是每位用户打开一个链接的方法，节省资源。 </p>
		<p>
				<br />查找关于数据库链接的资料</p>
		<p>你可以从几个数据字典视图中获得建立好的数据库链接的资料。DBA_DB_LINKS视图为每一定义的链接返回一行。OWNER 列和DB_LINK列分别显示了这一链接的所有者及名称。对公用数据库链接，OWNER列将包含'PUBLIC'。如果你建立固定用户链接，用户名应在DBA_DB_LINKS视图的USERNAME列里，但是口令只能从SYS.LINK$视图中看到。默认情况下，只有具有SELECT ANY TABLE系统权限的DBA能够访问SYS.LINK$视图查看口令。你应该保护访问那个视图的权限。ALL_DB_LINKS 视图和 USER_DB_LINKS视图与 DBA_DB_LINKS视图相类似-它们分别显示了你能够访问的所有链接及你所拥有的全部链接。最后，V$DBLINK动态性能视图向你显示出任意给定时间你-当前用户，打开的全部数据库链接。 </p>
		<p>
				<br />全局性的数据库名称 </p>
		<p>在分布式环境里，Oracle建议你的数据库链接名应与它们连接到的数据库的全局性名称相匹配。因此如果你正在连接到名称为GNIS.GENNICK.ORG的数据库，你应当将你的数据库链接命名为GNIS.GENNICK.ORG <br />为确定数据库的全局性名称，以SYSTEM登陆并查询GLOBAL_NAME视图： </p>
		<p>
				<br />SQL&gt; SELECT * FROM GLOBAL_NAME;</p>
		<p>GLOBAL_NAME<br />_______________<br />GNIS.GENNICK.ORG</p>
		<p>由于历史的原因，默认情况下，全局性名称与数据库链接名称的之间的链接不是强制性的。不过，你可以通过设置GLOBAL_NAMES的初始化参数为TRUE来改变这一行为。例如： </p>
		<p>
				<br />SQL&gt; SHOW PARAMETER GLOBAL_NAMES</p>
		<p>NAME TYPE VALUE<br />________________________________________________________<br />global_names boolean TRUE</p>
		<p>用于产生这个范例的事例要求你使用的数据库链接名，必须与目标数据库的全局性数据库名称相匹配。注意与一些Oracle文档中说的相反，关键是你的本地事例的GLOBAL_NAMES设置。如果你的本地事例中GLOBAL_NAMES=FALSE，你就能够使用数据库链接，而不用管它们是否与远程数据库的全局性名称相匹配。总的来说，如果你设置GLOBAL_NAMES=TRUE，你应该在你的所有事例中一律这么做。<br /></p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/72838.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-09-29 15:35 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/29/72838.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>some database object</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72757.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 29 Sep 2006 03:31:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72757.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72757.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/29/72757.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72757.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72757.html</trackback:ping><description><![CDATA[
		<p>1 sequence<br />  1)   automatically generatess unique numbers<br />   is a sharable object<br />   is typically used to create a primary key value<br />   replaces applicaition code<br />   speeds up the efficiency of accessing sequence<br />   create sequence sequence<br />   [increment by n]<br />   [start with n]<br />   [{maxvalue n |nomaxvalue}]<br />   [{minvalue n |nominvalue}]<br />   [{cycle|nocycle}] <br />   [{cache n |nocache}]</p>
		<p>   create sequence dept_deptin_seq<br />   increment by 10<br />   start with 120<br />   maxvalue 9999<br />   nocache<br />   nocycle<br />  2) Confirming Sequences<br />   verify your sequence values in the user_sequences data dictionary table<br />   select sequence_name,min_value,max_value,increment_by,last_number<br />   from user_sequences;<br />   the last_number display the next available sequence number if nocache is specified<br />  3)nextval and currval Pseudocolumns<br />    --nextval return thee next available sequence value,it return a unique value every time<br />it si referenced,even for different ueer;<br />    --currval obtains the current sequence value;<br />    --nextval must be issued for that sequence before curval contains a value;<br />  4) Using a Sequence<br />    -- Caching sequence values in the memory give faster access to these values;<br />    -- Gaps in sequence value can occur when<br />       a rollback occurs<br />       b the system crashes<br />       c A sequence us used in another table;<br />   5) alter sequence test increment by 10;<br />      you can change all properties of the sequence except the start with .<br />   6) remove sequence<br />      drop sequence test;<br />2 index<br />  1) how are indexes created<br />   Automatically : a unique index is created automatically when you create primary key or </p>
		<p>unique constraint in a table definition,<br />   Manually: user can create nounique index on column to speed up access to the rows.<br />   create index testindex on autoer(lanme);<br />  2) When to Create an index<br />   ypu should create an index if:<br />   . a column contains a wide range of values<br />   . a column contains a large number of null values<br />   . one or more columns are frequently used together in where clause or a join condition;<br />   . The table is large and most queries are expected to retrieve less than 2 to 4 percent </p>
		<p>of the rows;<br />   3) When not to create an index<br />   this usually not worth creating an index if:<br />   . the table is small<br />   . The columns are not often used as a condition in the query.<br />   . Most queries are expected to retrieve more than 2 to 4 percent of the rows in the </p>
		<p>table<br />   . the indexed columns are referenced as part of an expression.<br />   4)Confirming indexes<br />    . The user_indexes data dictionary view contains the name of the index and tis uniquess<br />    . the user_ind_columns view contains the index name,the table name,and the column name.<br />    select ic.index_name,ic_column_name,ic.column_position,ic_col_pos,ix.uniqueness<br />    from user_indexed ix,user_ind_columns ic<br />    where ic.index_name=ix.index_name<br />    and ic.table_name='employees';<br />  5)基于函数的索引<br />  . a function-based index is an index based on expressions<br />  . The index expression is built form table columns,constraints,SQL functions and user-</p>
		<p>defined functions<br />   create index testindex2<br />   on autors (upper(au_fname));<br />   <br />   select * from authors<br />   where upper(au_fname) like 'B%';<br />  6) remoe index<br />   drop index index_name;<br />3 synonyms<br />  Simplify access to objects by creating a synonym <br />   . Ease referring to a table ownerd by anther user<br />   . Shorten lengthy object names;<br />   create [publi] synonym synonym for object;<br /></p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/72757.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-09-29 11:31 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/29/72757.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用游标</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/28/72593.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Thu, 28 Sep 2006 07:32:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/28/72593.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72593.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/28/72593.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72593.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72593.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 erveroutput 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=$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 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/72593.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-09-28 15:32 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/28/72593.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>createing view</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72367.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 27 Sep 2006 10:30:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72367.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72367.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72367.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72367.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72367.html</trackback:ping><description><![CDATA[
		<p>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 </p>
		<p>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 </p>
		<p>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 distince 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 </p>
		<p>view by using the with check option clause.<br />  creaate 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 </p>
		<p>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 </p>
		<p>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 />  </p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/72367.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-09-27 18:30 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/27/72367.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用复合变量.</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72317.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Wed, 27 Sep 2006 07:46:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72317.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/72317.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/27/72317.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/72317.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/72317.html</trackback:ping><description><![CDATA[
		<p>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 erveroutput 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=$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 </p>
		<p>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 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;</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/72317.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-09-27 15:46 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/27/72317.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>including constraint</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/26/71973.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Tue, 26 Sep 2006 06:44:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/26/71973.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71973.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/26/71973.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71973.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71973.html</trackback:ping><description><![CDATA[
		<p>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     </p>
		<p>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 satify<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 </p>
		<p>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 </p>
		<p>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 </p>
		<p>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'</p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/71973.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-09-26 14:44 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/26/71973.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>creating and manipulation table</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71804.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Mon, 25 Sep 2006 09:59:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71804.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71804.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71804.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71804.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71804.html</trackback:ping><description><![CDATA[1 Table in the Oracle Database<br />1) User Tables:<br />  a Are a collection of tables created and maintained by the user<br />  b Contain user information<br /> 2) Data Dictionary<br />  a is a collection of table created and maintained by the Oracle Server<br />  b Contain database information<br />2 Querying the Data Dictionary<br /> 1)see the names of the table owned by the user<br />   select table_name from user_tables;<br /> 2) view distinct object types ownered by the user<br />   select distinct object_type from user_object;<br /> 3) view tables ,view ,synonyms and sequences owned by the user<br />   select * from user_catalog<br />3 Creating a Table by Ussing a Subquery Syntax<br /> create table tt3 <br /> as <br /> select * from authors<br />4 Teh alter table Statement<br /> 1) Add a new column<br />  alter table tt2 <br />  add(fname varchar2(20) default 'unkonown',<br />      address varchar2(30) null);<br /> 2)Modigying a Column's data type size and default value<br />  alter table dept80<br />  modigy (last_name varchr2(30))<br />  A change to thee default value affects onlly subsequent insertion to the table<br />  3) drop a column<br />  alter table dept80 <br />  drop column job_id;<br />  The set unseed Option<br />   a you use the set unused optoin to mark one or more columns as unused<br />   b you use the drop unused colimns options to remove the columns that are marked as<br />   as unused<br />   alter table tt2<br />   set unused colun fnamel;<br />   alter table table<br />   drop unused columns<br />5 Dropping a Table<br /> 1) All data and structure in the table is deleted<br /> 2) Any pending transaction are committed<br /> 3) All indexes are dropped<br /> 4) You cannot roll back the drop table statement<br />6 Changing the Name of an Object<br />  rename dept to detail_dept;<br />  you must be the owner of the object<br />7 Truncate a Table<br />  Remove all rows from the table<br />  release the storage space used by that table<br />  you cannot rollback row when using truncate<br />  alternatly ,you can remove row by using delete statement<br /><img src ="http://www.blogjava.net/kevinfriend/aggbug/71804.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-09-25 17:59 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/25/71804.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Data manipulation</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71781.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Mon, 25 Sep 2006 08:25:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71781.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71781.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/25/71781.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71781.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71781.html</trackback:ping><description><![CDATA[1 Data Manipulation Language<br />  1) A DML statement is executed when you:<br />     add new rows to a table<br />     modify existing row in a table<br />     remove existing rows from a table<br />  2) A transaction consist a collection dml statements form a logic unit of work<br />2 Using Explicit Default Values<br /> 1) default with insert<br /> insert into departments <br /> values(200,'ddd',default)<br /> 2) default with update<br /> update departments<br /> set manager_id=default where department_id=10<br />3 The Merge Statement<br /> 1)Provide the ability to conditionaly update or insert data into database<br /> 2)Perform a update if the row exists and an insert if it is a new row<br />   a Avoid update separatly<br />   b increase performance and ease of use<br />   c is useful in data warehousing application<br />   example<br />    merge into copy_emp c<br />    using employees e<br />    on (c.employee_id=e.employee_id)<br />    when mathched then<br />    update set<br />      c.first_name=e.first_name<br />      c.last_name=e.last_name<br />      ..............<br />      c.department_id=e.department_id<br />    when not matched then<br />    insert values(e.employeeid,e.first_name,......e.department_id);<br />4 Database Transactions<br /> 1)Begin when the first dml statement is executed<br /> 2)end with one of the following events<br />   a a commit or rollback statement is issued;<br />   b a ddl or dcl statement execute (commit automatically)<br />   c the user exist isqllplus<br />   d the system crashes<br /> 3) advantage of commit and rollback statemnt<br />   With commit and rollback statement ,you can <br />    a ensure data consistence<br />    b Preview data change before making change permant<br />    c group logic relate operatons<br />5 State of The Data Before commit or rollback<br /> 1) the previous state of the data can be recovered<br /> 2) The current user can review the result of the dml operation by using the select statment<br /> 3) other user can not view the result of the dml<br /> 4) the affected was locked ,other user cannot change the data within the affecteed row<br />6 Read Consistency<br /> 1) Read consistency guarantees a consistent view of the data at all times<br /> 2) Changes made by one user do not confilict with changes made by another user<br /> 3) Read consistency ensures that on the same data<br />    a Readers do not wait for writers<br />    b Writers do not wait for readers<br />7Locking<br />  1) Prevent destructive interaction between concurrent transactions<br />  2) Reqire no user action<br />  3) Automatically use the lowest level of restrictiveness<br />  4) Are held for the duration of the transaction<br />  5) Are of two types:explicit locking an implicit locking<br />8 Implicit Locking<br />  1)Two lock modes<br />    a Exclusive :Locks out other users<br />    b Share: Allows other users to accesss<br />  2)High level of data concurrency<br />    a DML:Table share,row exclusive<br />    b Queries: No locks required<br />    c DDL:Protects object definitions<br />  3)Locks held until commit or rollback<br /><img src ="http://www.blogjava.net/kevinfriend/aggbug/71781.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-09-25 16:25 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/25/71781.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sequence 的用法</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/24/71573.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Sun, 24 Sep 2006 08:08:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/24/71573.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71573.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/24/71573.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71573.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71573.html</trackback:ping><description><![CDATA[刚刚用sequence ，又忘了，呵呵，从网上找了一篇文章，写的不错，copy 在这里<br />1、Create Sequence  <br />你首先要有CREATE SEQUENCE或者CREATE ANY SEQUENCE权限，  <br />CREATE SEQUENCE emp_sequence  <br />    INCREMENT BY 1  -- 每次加几个  <br />    START WITH 1    -- 从1开始计数  <br />    NOMAXVALUE      -- 不设置最大值  <br />    NOCYCLE         -- 一直累加，不循环  <br />    CACHE 10;  <br /><br />一旦定义了emp_sequence，你就可以用CURRVAL，NEXTVAL  <br /> CURRVAL=返回 sequence的当前值  <br /> NEXTVAL=增加sequence的值，然后返回 sequence 值  <br />比如：  <br />  emp_sequence.CURRVAL  <br />  emp_sequence.NEXTVAL  <br /><br />可以使用sequence的地方：  <br />- 不包含子查询、snapshot、VIEW的 SELECT 语句  <br />- INSERT语句的子查询中  <br />- NSERT语句的VALUES中  <br />- UPDATE 的 SET中    <br /><br />可以看如下例子：  <br />INSERT INTO emp VALUES   <br />(empseq.nextval, 'LEWIS', 'CLERK',7902, SYSDATE, 1200, NULL, 20);  <br /><br />SELECT empseq.currval     FROM DUAL;  <br /><br />但是要注意的是：  <br />- 第一次NEXTVAL返回的是初始值；随后的NEXTVAL会自动增加你定义的INCREMENT BY值，然后返回增加后的值。CURRVAL 总是返回当前SEQUENCE的值，但是在第一次NEXTVAL初始化之后才能使用CURRVAL，否则会出错。一次NEXTVAL会增加一次SEQUENCE的值，所以如果你在同一个语句里面使用多个NEXTVAL，其值就是不一样的。明白？  <br /><br />- 如果指定CACHE值，ORACLE就可以预先在内存里面放置一些sequence，这样存取的快些。cache里面的取完后，<a class="channel_keylink" href="http://www.easylib.org/programme/database/oracle/">oracle</a>自动再取一组到cache。 使用cache或许会跳号， 比如数据库突然不正常down掉（shutdown abort),cache中的sequence就会丢失. 所以可以在create sequence的时候用nocache防止这种情况。  <br /><br />2、Alter Sequence  <br />你或者是该sequence的owner，或者有ALTER ANY SEQUENCE 权限才能改动sequence. 可以alter除start至以外的所有sequence参数.如果想要改变start值，必须 drop  sequence 再 re-create .  <br />Alter sequence 的例子  <br />ALTER SEQUENCE emp_sequence  <br />    INCREMENT BY 10  <br />    MAXVALUE 10000  <br />    CYCLE    -- 到10000后从头开始  <br />    NOCACHE ;  <br /><br /><br />影响Sequence的初始化参数：  <br />SEQUENCE_CACHE_ENTRIES =设置能同时被cache的sequence数目。   <br /><br />可以很简单的Drop Sequence  <br />DROP SEQUENCE order_seq;  <br /><img src ="http://www.blogjava.net/kevinfriend/aggbug/71573.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-09-24 16:08 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/24/71573.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>subqueries</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71344.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 22 Sep 2006 08:25:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71344.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71344.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71344.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71344.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71344.html</trackback:ping><description><![CDATA[
		<p>1 Guidelines for Using Subqueries<br /> a Enclose subqueries in parenttheses<br /> b placce subqueries on the right side of the comparision condition<br /> c the order by clause in the subquery is not needed<br /> d using single-row operators with single-row subqueries and use multiple -row operator with multiple-row subqueries .<br />  single-row subqueries can work as a expression,and muitiple-row subqueries can only be used with in all any ,i will talk it later<br />  select last_name where job_idd=(select job_id<br />                                  from employees<br />                                  where imployee_id=141)<br />2 The HAVING CLause with Subqueries<br /> a The Oracle server execute subqueries first<br /> b The Oracle return result into the HAVING clause of the main query<br />  select department_id,min(salary)<br />  from employee<br />  group by department_id<br />  having min(salary)&gt;<br />                     (select min(salary)<br />                      from employees<br />                      where department_id=50);<br />3 Multiple-Row Subqueries <br />  a Return  more than one row<br />  Using mutiple-row comparsion operator<br />  select employee_id<br />  from employees<br />  where salary&lt;any<br />                  (select salary<br />                   from employees<br />                   where job_id='ddd')</p>
		<p>  select employee_id<br />  from employees<br />  where salary&lt;all<br />                  (select salary<br />                   from employees<br />                   where job_id='ddd')<br />   select emp.last_name<br />   from employees emp<br />   where emp.employee_id not in<br />                               (select mgr.manager_id<br />                                from employees mgr)<br /></p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/71344.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-09-22 16:25 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/22/71344.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>jointable</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71323.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 22 Sep 2006 06:55:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71323.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71323.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71323.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71323.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71323.html</trackback:ping><description><![CDATA[1 Jioning Tables Using Oracle Syntax<br />Using a join to query data form more than one table<br />select table1.column,table2,column <br />from table1,table2<br />where table1.column1=table2.column2 .<br />2 outjoin <br /> 1)You use an outer join to also see rows that do not meet the join condition<br /> 2)The Outer join operator is the plus sign(+)<br />   a left join<br />     select tabl1.column,table2,column<br />     from table1,table2<br />     where table1.column(+)=table2.column<br />  b  right join<br />     select table1.column,table2.column<br />     from table1,table2<br />     wheretable1.coulmn=table2.column(+)<br />  3) self join<br />     select worker.last_name||'works for'||manager.last_name<br />     from  employees owrker,employees manager<br />     where worker.manager_id=manager.employee_id;<br /> <br />3 Joining Tables Using SQL:1999 Syntax<br />  Use a join to query data from more than one table<br />  1) Creationg Cross Joins<br />   a The cross join clause produces thee cross product of two tables<br />   b This is the same as Cartesian product between the two tables<br />   select last_name,department_name<br />   from employees<br />   ccross join departments<br />  2) Creating Natual Joins<br />   a The Natual join clause is bassed on all columns in the two tables that have the same name<br />   b it select rows from the two tables that have the equal values in all matched columns<br />   c if the columns having the same name and have the different data types in an error is returned.<br />   select department_id,department_name,location_id,city<br />   from departments<br />   natual join locations<br /> 3) using clause<br />   select e.employee_id,e.last_name<br />   from employees e join departments d<br />   using (department_id);<br /> 4) Creating joins with thee on clause<br />  a The join condition for thee natual join is basically an equaljoin of all column with the same name.<br />  b To specify arbitrary condition or specify columns to join, the on clause is userd<br />  c The join condition is separated from other search conditions<br />  d The on claus make code easy to understand. <br />  select e.employee_id,e.last_name,e.department_id,<br />  from employees e join departments d<br />  on (e.department_id=d.department_id);<br />  <br />  from employe<br />  join departments d<br />  on d.department_id=e.department_id<br />  join locations l<br />  on d.location_id=l.location_id<br /> 5) INNER Versus OuTER Joins<br />  a In SQL:1999,the join of two tables returning only matched rows is an inner join<br /> 6) FULL OUTER JOIN<br />  select e.last_name,e,department_id,d.department_name<br />  from employees e<br />  full outer join departments d<br />  on (e.department_id=d.department_id);<br />  <img src ="http://www.blogjava.net/kevinfriend/aggbug/71323.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-09-22 14:55 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/22/71323.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sql function</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71279.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 22 Sep 2006 03:50:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71279.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71279.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71279.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71279.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71279.html</trackback:ping><description><![CDATA[
		<p>1 "'<br />2 ||<br />3 isql*plus  <a href="http://127.0.00.1/isqlplus">http://127.0.00.1/isqlplus</a><br />4 desc author<br />5 initcap('SQL Course')<br />  INSERT('JellwWord','W')  6<br />   LPAD (salary,10,'*')  *****24000<br />   RPAD (salary,10,'*')  24000*****<br />   TRIM ('H' from 'HolloWorld') olloWord<br />   substr('helloword',1,5)  hello<br />   substr('helloword',-1,5) oword<br />6  Number Functions<br />   round(45.926,2)   45.93<br />   round(45.926,-2) 0<br />   round(55.926,-2) 100<br />   trunc(45.926,2)   45.92<br />   mod(1600,300)  100<br />7 data function<br />   systdate<br />   (sysdate-hire_date)/7 as weeks<br />   months_between  number of months between two dates<br />   months_between ('01-sep-95','11,jan-94')  19.6774194<br />   add_months      add calendar months to date<br />   add_months('11-JAN-94',6)  '11-JUL-94'<br />   next_day        next day of the date specified<br />   next_day('01-SEP-95','FRIDAY') '08-SEP-95'<br />   last_day        last day of the month<br />   last_day('01-feb-95')  '28-feb-95'<br />   round           round date<br />   assume sysdate='25-jul-95'<br />   round(sysdate,'month') 01-aug-95<br />   round(sysdate,'year')  01-JAN-96<br />   trunc           truncate date<br />   trunc(sysdate,'month') 01-Jul-95<br />   trunc(sysdate,'month') 01-JAN-95 <br />8  Conversion Functions  <br />  1) implicit data typ conversion<br />   varchar2 or char  ---number<br />   varchar2 or char  ---date<br />   numbeer           ---varchar2<br />   date              ---varchar2<br />  2) to_char(date,'format')<br />  format: <br />    YYYY Full year in numbers<br />    YEAR Year spelled out<br />    MM   Two-digit value for month<br />    MONTH Full name of the month<br />    MON  THree-letter abbreviation of the month<br />    DY   Three-letter abbreviation of the day of the week<br />    DAY  Full name of the day of hte week<br />    DD   Numberic day of the month<br />    HH24:MI:SS AM  15:45:32:PM<br />    DD "of"  MONTH 12 of october<br />  3) to_char function with number  <br />   TO_CAHR(number,'format_model')<br />   These are some of the format elements you can use with the to_char function to display number as a character.<br />    9 Reqresents a number<br />    0 Forces a zero to be displayed<br />    $ Places a flationg dollar sign<br />    L Uses the floating local currency symbol<br />    . Prints a decimal point<br />    , Print a thousand director<br />  select to_char(qtym,"$999.99")<br />  4) Using t_number and to _date functions<br />   a converting a character string to a number format using to_number function<br />   to_number(char,"format")l<br />   b converting a character string to a date format<br />   to_date(char,"format")<br />5 Nesting Functions<br />.Single-row function can be nested to many level<br />.Nested function can be evaluated from deepest level<br />6General Function<br />These function work with any data type and pertain to using nulls<br />nvl(expr1,expr2);<br />nvl2(expr1,expr2,expr3)<br />nullif(expr1,expr2)<br />coalesce(expr1,expr2,,,,exprn)<br /> 1) nvl function<br /> convert a null to an actual function<br /> a Data type can be used are data character and number<br /> b Data types must match                               <br /> (set wrap off<br />  set line 1000<br /> )<br /> 2)Using the COALESCE Function<br /> a The advantage of the coalesce function over nal function is that coalesce function can take multiple alternative value<br /> b If the first value is not null, it return that expression,otherwise,it does a coalesce of remaining expressions<br />6 Conditional Expressions<br /> a Provide the use of if-then-else logic<br /> b use two methods: case expression decode function<br />  select last_name,job_id,salary, <br />         case job_id when 'it' then 1*salary<br />                      when 'manager' then 1.2*salary<br />         else salary end;<br />  from employee.</p>
		<p>  select last_namek,job_id,salary,<br />         decode(job_id,'it' ,1*salary,<br />                        'manager',1.2*salary,<br />                salary)<br />   from employees<br />   </p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/71279.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-09-22 11:50 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/22/71279.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Aggregating Datas Using Group Functionbs.</title><link>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71278.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 22 Sep 2006 03:49:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71278.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/71278.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/09/22/71278.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/71278.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/71278.html</trackback:ping><description><![CDATA[
		<p>1 What Are Group Functions<br />Group functions operatee on sets of rows to give one result per group<br /> 1)agg,count,max,min,stddev,sum,variance<br /> select avg(salary),max(salary),min(salary),sum(salary)<br /> from employees<br /> where job_id like '%REP%'</p>
		<p> select count(*) from<br /> select count(address) from authors<br /> count the valid count of the address (exclude the null value)<br /> 2) Using theDISTINCT Keyword<br />  count(distinct expr) return thee number of the distinct non-null value of the expr<br />  select count(distincee department_id) from employees <br /> 3)Group functions and null values<br />  group functions ignore null values in the clumn<br /> 4) Using thee NVL Function with Group Functions<br />  The nul function force group funtion to include null values<br />  select avg(nvl(commission_pct,0)) from employees<br />2 Creating Groups of Data <br />  1)<br />  a Divide rows in a table into smaller groups by using the group by clause<br />  b All coulmns in the select list that are not in group function must be in the group by clause<br />  select department_id,avg(salary)<br />  from employees<br />  group by department_id;<br />  2) Grouping by More Than One Column<br />  3) Ilegal Queries Using Group Functions<br />   a You cannot use thee where clause to restrict groups<br />   b You use thee having clause to restrict groups<br />   c you cannot use group functions in the where clause<br />  4)Excluding Group Resdults:The Having Clause<br />   Use the HAVING clause to restrict groups<br />   a Rows are grouped<br />   b The group functions is applied<br />   c Groups matcching the Having clause are display<br />  select department_id,max(salary)<br />  from employees<br />  group by department_id<br />  having max(salary)&gt;10000<br /> 5) Nesting Group function<br /> select max(avg(salary))<br /> from employees<br /> group by department_id; </p>
<img src ="http://www.blogjava.net/kevinfriend/aggbug/71278.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-09-22 11:49 <a href="http://www.blogjava.net/kevinfriend/archive/2006/09/22/71278.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>oracle 结构设计</title><link>http://www.blogjava.net/kevinfriend/archive/2006/08/11/62932.html</link><dc:creator>康文</dc:creator><author>康文</author><pubDate>Fri, 11 Aug 2006 02:47:00 GMT</pubDate><guid>http://www.blogjava.net/kevinfriend/archive/2006/08/11/62932.html</guid><wfw:comment>http://www.blogjava.net/kevinfriend/comments/62932.html</wfw:comment><comments>http://www.blogjava.net/kevinfriend/archive/2006/08/11/62932.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/kevinfriend/comments/commentRss/62932.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/kevinfriend/services/trackbacks/62932.html</trackback:ping><description><![CDATA[1 条件分之语句<br />  1 简单条件判断<br />  declare <br />   v_sal number(6,2);<br />  begin<br />   select sal into v_sal from emp<br />   where lower(ename)=lower('&amp;&amp;name');<br />   if v_sal&lt;2000 then <br />    update emp set sal=v_val+200<br />    where lower(ename)=lower('&amp;name');<br />   end if;<br />  end;<br /> 2 二重条件分支<br />  if v_comm&lt;&gt;0 then<br />      .....<br />  else<br />     ........<br />  end if;<br /> 3 多重条件分支<br />  IF   THEN<br />  ELSIF   THEN<br />  ELSIF   THEN<br />  ELSE<br />  END IF;<br />2 case 语句<br />  1 在case 语句中使用单一选择符进行等值比较<br />    declare <br />      v_deptno emp.deptno%type<br />    begin<br />      v_deptno:=&amp;no;<br />      case v_deptno<br />         when 10 then<br />           update emp...<br />         when 20 then<br />           update ......<br />         else<br />          dems_out.put_line('不存在该部门');<br />      end case;<br />    end;<br />  2 在case 语句中使用多种比较条件<br />    declare <br />      v_sal emp.sal%type<br />      v_ename emp.ename%type<br />    begin<br />     select ename ,sal into vv_ename,v_sal<br />     from emp where empno=&amp;no;<br />     case<br />       when v_sal&lt;1000 then<br />         update emp set ...<br />       when v_sal&lt;2000 then<br />     end case;<br />3 循环语句<br />  1 基本循环<br />   declare<br />    i INT:=1;<br />   begin<br />    loop<br />     insert into temp valuse(1);<br />     exit when i=10;<br />     i:=i+1;<br />    end loop;<br />   end;<br />  2 while 循环<br />    while i&lt;=10 loop<br />      insert into tem valuse(i);<br />      i:=i+1;<br />     end loop;<br />  3for 循环<br />    for i in reverse 1..10 loop<br />      insert into temp values(1);<br />    end loop;<br />4 顺序控制语句<br />  1 goto <br />    goto label_name;<br />    loop<br />      ...<br />      goto end_loop;<br />    &lt;&lt;end loop&gt;&gt;<br />     dbms_output<br />   2 null 语句不会执行任何操作，并且会直接将控制传递道下一条语句<br />    if v_sal&lt;3000 then<br />      update emp set .....<br />    else <br />      null;<br />    end if;<img src ="http://www.blogjava.net/kevinfriend/aggbug/62932.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-08-11 10:47 <a href="http://www.blogjava.net/kevinfriend/archive/2006/08/11/62932.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>