??xml version="1.0" encoding="utf-8" standalone="yes"?>
grant connect,create table to test1;
conn cyts_cc/cyts_cc@orcl2000;
create table(
id int)
tablespace user;
ERROR 位于W?1 ?
ORA-01950: 表空?USERS'中无权限
conn cyts_cc/cyts_cc@orcl2000;
alter user test1 quota 1M on users;
create tab
(id int);
success
alter user test1 account lock;
conn test1/test1@orcl2000;
ERROR:
ORA-28000: the account is locked
1 Database Schema
a schema is a named collection of objects
b user is created and a corresponding schema is created
c user can be associated only with one schema
d username and schema are often userd interchangely.
2 Checklist for creating users
a idntfigy tablespaces in which the usr nedds to store objects
b decide on quotas for each tablespace
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.
d create user
e grant privileges and roles to user
desc dba_users;
select * from dba_users;
3 Creating a new user:
Database Authentiacation
set the initial password
create user aaron
identified by soccer
default tablespace data
temporary tablespace temp
guota 15m on data
password expire;
alter database default temporary tablespace temp;
4 Creating a new user operating System Authentication
os_authent_prefix initialllization parameter specifies the format of the username
defauts to ops$
create user arron
identified externally
default tablespace users
temporary tablespace temp
quota 15m on data
password expire;
conn /
show parameter os
os_authent_prefix string OPS$
create user ops$test3
identified externally
default tablespace us
temporary tablespace
quota 10m on users
thee test2 is an user of os ,which the oracle is installed.
5 Changing user quota on tablespace
alter user test3 quota 4m on users;
you cann't grant quota on temp and undotbs.
alter quota 0 on uers -- means that no new table space can be allocated and cannot change the exist object in the tablespaces
6 drop user
you cannot drop user who has connected to oracle
drop user (cascade)
7 Obtaining User information
information about uers can be obtained by qerying the data dictionary
dba_users
名称
-----------------------------
USERNAME
USER_ID
PASSWORD
ACCOUNT_STATUS
LOCK_DATE
EXPIRY_DATE
DEFAULT_TABLESPACE
TEMPORARY_TABLESPACE
CREATED
PROFILE
INITIAL_RSRC_CONSUMER_GROUP
EXTERNAL_NAME
dba_ts_quotas
名称
---------------
TABLESPACE_NAME
USERNAME
BYTES
MAX_BYTES
BLOCKS
MAX_BLOCKS
4) 带有 in out 参数
create or replace function result
(num1,number,num2 in out nu8mber)
return number
as
v_result number(6);
v_remainder number;
begin
v_result:=num1/num2;
v_remainder:=mod(num1,num2);
num2:=v_remainder;
retrun v_result;
exception
when zero_divide then
raise_application_error(-20000,'zero divied');
end;
5) 函数调用的限?br /> -- 在sql 语句中只能调用存储函?br /> -- 在sql 语句中只能调用带有输入参数in Q而不能有输出参数out 和in out 参数的函?br /> -- 在sql 语句中调用的函数的参数必L标准的sql 数据cdQ不能是pl/sql 所Ҏ的数据类?br /> -- 在sql 语句中调用的函数不能包含insertQupdate 和delete
6) 查看源代?br /> set pagesize 40
select text form user_source where name='result';
7) 删除函数
drop function result;
3 理子程?br /> 1) 列出当前用户的子E序
select object_name,created,status form user_objects
where object_type in ('procedure','function');
2)列出子程序源代码
select text from user_sorce where name='raise_salary'
3)cd子程序编译错?br /> -- show errors
--使用数据字典user_errors 定错误原因和位|?br /> select line||'/'||position as "line/col",text error
from user_errors where name='raise_salary';
4) 列出对象的依赖关p?br /> -- 使用 user_dependenciess 定直接依赖关系
select name,type from user_dependencies
where referenced_name='emp'
-- 使用 deptree ?ideptree 定依赖和见解依赖关p?br /> select nested_level,name,type from deptree;
5) 重新~译子程?br /> 当被应用对象的结构被修改以后Q就会将相关依赖对象转变为无效invalid Q需要重新编?br /> 1
alter table emp add remark varchar2(100);
2
select object_name,object_type from user_objects
where status='invalid'
3
alter procedure add_employee compile;
alter view dept10 compile;
alter function get_info compile;
5 set operator guidelines
. teh expressions in the select list must match in number and data type;
. Parentheses can be used to alter the sequence of the execution
.The order by clause:
can appear only at the very end of the statement
will accept the column name,aliases from thee firest select statement ,or thee positional notation
.Duplicate row are atuomatically eliminated except in union all.
.Column names from the first query appear in the result
.The output is sorted in ascending order by default except in union all
6 matching the select statement
select department_id,to_number(null),location,hire_date
from employees
union
select department_id,location_id,to_date(null)
from departments;
select employee_id,job_id,salary
from employees
union
select employee_id,job_id,0
from job_history;
7 Controlling the order of the rows
select 'sing' as "my dream" ,3,a_dummy
from dual
union
select 'like''d like to teach',1
from dual
union
select 'the world to',2
from dual
order by 2;
end;
)
3) 限制行触发器
当用行触发器,默认情况下会咱每个被作用行上七星一ơ触发器代码Qؓ了时得再特定条g下执行行触发器代码,需要用when 子句
create or replace trigger tr_sal_change
after update of sal on emp
for each row
when(old.job='salesman')
declare
v_temp int..
2 dml 触发器用注意事?br /> 触发器代码不能从触发器所对应的基表中d数据
3 dml 触发?br /> Z保证数据库满特定的商业规则或企业逻辑Q可以用约束,触发器和子程序。约束性能最好,实现最单,所以ؓ售选,如果触发器不盟实玎ͼ可以选择触发器?br /> dml 触发器可以用于实现数据安全保护,数据审计Q数据完整性,参照完整性,数据复制{功能?br /> 1) 控制数据安全
create or replace trigger tr_emp_time
before insert or update or delete on emp
begin
if to_char(sysdate,'hh24') not between '9' and '17' then
raise_application_error(-20101,'not work time');
end if;
end;
2) 实现数据审计
使用数据审计只能审计sql 操作Q而不会记载数据变?br /> audit insert,update,delete on emp by access
3)实现数据完整?br /> 首选约?alter table emp add constraint ck_sal check (sal>=800),但是在有些情况下只能使用触发器来实现数据完整?br /> create or replace trigger tr_check sal
before update of sal on emp
for each row
when (new.sla<old.sal or new.sal>1.2* old.sal)
begin
raise_application_error(,,,,,,)
end;
3) 使用引用完整?br /> 采用 on delete cascade 可以q行集联删除Q但是却不能q行集联更新。采用触发器实现集联更新
create or replace trigger tr_update
after update of sal on emp
for each row
begin
update emp set depno=:new.deptno where dentno=:old.deptno;
end;
4 建立instead of 触发?br /> 对于单视囑֏以直接进行insert update 和delete {操作,但是对于复杂视图不允许进行insertQupdate 和delete 操作?br /> 满一下条件的为复杂视?br /> h操作集合W?unionQunion all QintersectQminus
h分组函数 minQmaxQavgQsumQcount
hgroup by connect ~译 或start with
hdistinct
hq接
Z在复杂视图上执行dml 操作Q必要Zinstead-of 触发器,建立insteadQof 触发器后Q就可以Z复杂视图执行insertQupdate和delete 语句?br /> instead of 选项只用于视图
Z视图建立触发器时Q不能定义before ?after
在徏立视图时不能指定 with check option
当徏立instead of 触发器时Q必L定for each row 选项
1) 建立复杂视图dept_emp
create or replace view dept_emp as
select a.deptno,a.dname,b,empno,b,ename
from dept a,emp b
where a,deptno=b.deptno;
2) 建立 insteadQof 触发?br /> create of replacee trigger tr_instead_of_dept_emp
instead of insert on dept_emp
for each row
declare
v_temp int;
beegin
select count(*) into v_temp from dept where deptno=:new.deptno;
if v_temp=0 then
insert into dept(deptno,dname) values(:new.deptno,:new.dname);
end if;
select count(*)into v_temp from emp where empno=:new.empno;
if v_temp=0 then
insert into emp(empno,ename,deptno)
values(:new.deptno,:new.ename,:new.deptno);
end if;
end;
可以对视图执行insert 操作?br /> insert into dept_emp values(50,'admin','1223','mary')
5 理触发?br /> 1) 昄触发器信?br /> select trigger_name,status from user_triggers
where table_name='emp';
2)止触发?br /> alter trigger tr_check_sal disable;
3) Ȁz触发器
alter trigger tr_check_sal enable;
4) 止或激z表上的所有触发器
alter table emp disable all triggers;
alter table emo eanble all triggers;
5)重新~译触发?br /> alter trigger tr_check_sal compile;
6) 删除触发?br /> drop trigger tr_check_sal;
exec grant_sys_priv('create session','scott');
3 使用execute immediate 处理dml 操作
1) 处理无占位符和returning 子句的dml 语句
delcare
sql_stat varchar2(100);
begin
sql_stat:='update emp set sal=sal*1.1 where deptno=44';
execute immediate sql_stat;
end;
2) 处理包含占位W的dml语句
delare
sql_stat varchar2(100);
begin
sql_stat:='update emp set sql=sql*(1+:percent/100)'
||'where deptno=:dno';
execute immediate sql_stat using &1,&2;
end;
3) 处理包含returning 子句的dml语句
declare
salary number(6,2);
sql_stat varchar2(200);
begin
sql_stat:='update emp set sal=sal*(1:percent/100)'
||'where empno=:eno returning sal into :salary';
execute immediate sql_stat using &1,&2;
returning into salary;
end;
输入1的?15
输入2的?2222
新工资;2223
4) 使用execute immediate 处理单行查询
declare
sql_stat varcchar2(100);
emp_record emp%rowtype;
begin
sql_stat:='select * from emp where empno=:eno';
execute immediate sql_stat into emp_record using &1;
end;
3 处理多行查询语句
declare
type empcurtyp is ref cursor;
emp_cv empcurtyp;
emp record emp%rowtype;
sql_stat varchar2(100);
begin
sql_stat:='select * from em where deptno=:dno';
open emp_cv for sql_stat using &dno;
loop
fetch emp_cu into emp_record;
exit when emp_cv%notfound;
end loop;
close emp_cv;
end;
4 在动态sql 中用bulk语句
1) ?execute immediate 语句中用动态bulk 语句
declare
type ename_table_type is table of emp.ename%type
index by binary_integer;
type sal_table_type is table of emp.sal%type
index by binary_integer;
ename_table ename_table_type;
sa_table sal_table_type;
sal_stat varchar2(100);
begin
sql_stat:='update emp set sal=sal*(1+:percent/100)'
|| 'where deptno=:dno'
||'returning ename,sal into :name,:salary';
execut immediate sql_stat using &percent,&dno
returning bulk collect into ename_table,sal_table;
for i in 1..ename_table.count loop
....
end loop;
end;
2) 使用bulk 子句处理多行查询
sql_stat:='select ename from emp where deptno=:dno';
execute immediate sql_stat bulk collect into ename_table using &dno;
3) 在fetch 语句中用bulk 子句
declare
type empcurtyp is ref cursor;
emp_cv empcurtyp;
type ename_table_type is table of emp.ename%type;
index by binary_integer;
ename_table ename_table_type;
sql_stat varchar2(100);
begin
sql_stat:='select ename from emp where job:=title';
open emp_cv for sql_stat using '&job';
fetch emp_cv bulk collect into ename_table;
4) 在forall 语句中用bulk 子句
declare
type ename_table_type is table of emp.ename%type;
type sla_table_type is table of emp.sal%type;
ename_table ename_table_type;
sal_table sal_table_type;
sql_stat varchar2(100);
begin
ename_table:=ename_table_type('scott','smith','clark');
sql_stat:='update emp set sal=sal*1.1 where ename=:1'
||'returning sal into :2';
forall i in 1..ename_table.count
execite immediate sql_stat using ename_table(i)
returning bulk collect into sal_table;
end;
2 Starting Point
.Specifies the condition that must be met
.Accepts any valid condition
3 Waling the Tree
connect by prior column1=column2
walk from the top donw ,using the employees table
top donw
column1=parentkey
column2=childkey
bottom up
column1=child key
column2=parent key
select level,last_name
from employees
start with last_name='king'
connect by prior employee_id=manager_id;
alter profile profile1 limit
passowrd_lock_time 1/24 --one hour
5 passowrd expiration and aging
passwowd_life_time lifetime of the passowrd in days after which the password expires(有效?
password_grace_time grace period in days for changing the password after the first successful login afteer the password has expired(锁定?
e.g
alter profile profile1 limit
password_life_time 2
password_grace_time 3;
6 password history
password_reuse_time:number of days before a passowrd and be resued
password _reuse_max:maxum number of times password can bee reused
e.g
alter profile profile1 limit
password_reuse_time 10
password_reuse_max 3;
7passowrd Verification(study latter)
8drop a profile
drop profile profile1 (cascade);
the user will use the default profile.it will take effect on the new session.
9 Resource Management
Resource mangement limits can be enforced at the session level,the call level or both
limits can be defined by profiles using the create profile command
enable resource limints with the
.resource_limit initialization parameter
alter system command
e.g
alter system set resource_limit=true;
10 setting a Resdource limits at session level
cup_per_session : total cpu time measured in hundredths of seconds (癑ֈ之一U?
sessions_per_user: number of coucurrent sessions allowed for each username
connect_time:elapsed connect time measured in minutes
idle_time :periods of inactive time measured in minutes
logical_reads_per_session: number of data blocks
private_sga :measure in reads
e.g
alter profile profile1 limit
cpu_per_session 100000
connect_time 60
idle_time 5;
alter user test profile profile1
11 Setting Resource limits at call level
e.g
alter profile profile1
cpu_per_call 1000 -- cup time per call in
logical_reads_per_call --number of data balock that can be read per call
create profile develper_prof limit
session_per_user2
cpu_per_session 10000
idle_time 60
connect_time 480
12 Managing Resources using database resource manager
1)Provides the oracle server with more control over resorce management decisions
2)elements of database resorcee manager
resource consumer group
resourcee plan
resource allocation method
resource plan directives
3)dbms_resource_manager package is uerd to create and maintain elements
4)requires administer_resource_manager privilege
desc dbms_resoource_manager
13 0btaining password and resource limits informaiton
information about password and resource limits can be obtained by querying the data dictonary
dba_users
select * from users;
dba_profiles
select * from dba_profiles where profile='PROFILE1'
SQL> create user testuser
2 identified by test;
User created
SQL> conn testuser/test@orcl2000
Not logged on
SQL> grant access session to testuser;
grant access session to testuser
Not logged on
SQL> conn digit_cc/digit_cc@orcl2000
Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0
Connected as digit_cc
SQL> grant create session to testuser;
Grant succeeded
SQL> conn testuser/test@orcl2000;
Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0
Connected as testuser
4 user System privileges
once a user is created,the dba can grant specific system privileges to a user
grant privilege[,privilege...]
to user [,user|role,public...];
DBA can grant a user specific system privileges
grant create session,create table,create sequence,create view to scott;
5 creating and granting privileges to role
' Create a role
create role manager;
.grant privileges to a role
grant create table,create view to manager
.Grant a role to user
grant manager to kochar;
SQL> create role testrole;
Role created
SQL> grant create table,create view,create sequence to testrole;
Grant succeeded
SQL> grant testrole to testuser;
6 change your password
you can change your password by using the alter user statement;
alter user scott
indetified by lion;
7 object privileges
object privileges vary from object to object
an owner has all the privilege to the object
an owner can give specific privilege on that owner object
grant select on auther to testuser;
grant select on outher to testuser with grant option -- testuser also can grant it to
other user;
grant update(department_name,location_id)
on departments
to scott,manager;
8 how to revoke object privileges
--you use the revoke statement to revoke privileges granted to other users
--privileges granted to other users through the with grant option clause are also revoked.
revoke privilege {[,privilege...]|all} on object
from {user[,user....]|role|public}
[cascade constraints]
revoke select on author from user;
9 Database Links
Database link allow user to access data in the remote database;
SQL> create database link kjw1
2 connect to digit_cc identified by digit_cc
3 using 'orcl2000';
Database link created
SQL> select * from digit_cc.table_action@kjw1;
在一个分布式的环境里Q数据库链接是定义到其它数据库的路径的一个重要方法,使得q程处理天衣无缝?/p>
要获得数据库链接的更深奥的知识,查看Oracle8i SQL ReferenceQOracle8i SQL参考)和Oracle8i Concepts QOracle8i概念手册Q。详l资料的另一个极好的来源是Oracle8i Distributed Database SystemsQOracle8i分布式数据库pȝ手册Q?/p>
今天许多q行Oracle的机构有不止一个Oracle数据库。有时不原计划是否q样Q一个数据库中的数据可能与另一数据库中的数据关联。出现这U情冉|Q你可以链接q两个数据库使得用户或应用程序可以访问所有数据,好象它们在一个数据库中。当你这么做Ӟ你就有了一个分布式数据库系l?
如何两个数据库链接在一起呢Q用一个数据库链接来完成。数据库链接是定义一个数据库到另一个数据库的\径的对象。数据库链接允许你查询远E表及执行远E程序。在M分布式环境里Q数据库链接都是必要的?
单案?/p>
数据库链接的目的是定义一条到q程数据库的路径Q你可以通过在本地执行一条SQL语句来用那个数据库中的表和其它的对象。例如,你在一个远E数据库上有一个称之ؓ"geographic feature name"的表Q而你惛_已连接到你本地数据库的情况下讉K那些数据。数据库链接正是你所需要的。在建立它之前,你必L集如下信息:
一个网l服务名Uͼ你的本地数据库事例能够用它来与q程事例相连接远E数据库上的有效用户名和口o|络服务名称是每一个数据库链接必需的。每一ơ你从客hPC使用SQL*Plusq接C的数据库旉要用服务名U。在那些情况下,你提供给SQL*Plus的网l服务名U是通过在你的客h上的nsnames.ora文g中查扑֮们来解析的。在数据库链接中使用的网l服务名UC是如此,除非是那些名字是使用ȝ在服务器上的tnsnames.ora文g来解析?
在你定义数据库链接时指定的用户名和口令,用于建立与远E事例的q接。不需编码用户名和口令,建立数据库链接也是可能的甚至是值得选取的。既然这P现在我们注意q个最直接的例子?
下列语句建立了一个数据库链接Q它允许讉K客户帐户Q这个帐h事先在GNIS数据库徏好的Q?/p>
CREATE DATABASE LINK GNIS
CONNECT TO GUEST IDENTIFIED BY WELCOME
USING 'GNIS';
链接名称GNIS紧随LINK关键字。当q接到远E事例时QCONNECT TO...IDENTIFIED子句指定UEST/WELCOME作ؓ用户名和口o使用 。USING子句指定通过|络服务名称GNIS建立q接。用这一链接Q现在你可以在远E数据库上查询数据。例如:
SQL> SELECT GFN_FEATURE_NAME
2 FROM GNIS.FEATURE_NAMES@GNIS
3 WHERE GFN_FEATURE_TYPE='falls'
4 AND GFN_STATE_ABBR='MI'
5 AND GFN_COUNTY_NAME='Alger';
GFN_FEATURE_NAME
_________________
Alger Falls
Au Train Falls
Chapel Falls
Miners Falls
Mosquito Falls
Tannery Falls
..
在SELECT语句中@GNIS紧随表名Uͼ说明GNIS.FEATURE_NAMES表是在远E数据库Q应该通过GNIS链接讉KQ链接类型Oracle支持几种不同cd的链接。这些类型相互重叠,有时难以通过选项q行分类。当你徏立数据库链接Ӟ你需要从下面选取Q?
PublicQ公用)或Private Q私有)链接
权限c? Fixed UserQ固定用P, Connected UserQ连接用P?Current UserQ当前用P
Shared LinkQ共享链接)?Not Shared LinkQ非׃n链接Q?
每次创徏数据库链接时Q你要自觉不自觉地做q三U选择?
公用链接与私有链接相Ҏ
公用数据库链接对所有的数据库用户开放访问权。前面显C的是私有数据库链接Q它只对建立它的用户授权。公用数据库链接更ؓ有用Q因为它使你不必为每一个潜在用户创建单独的链接。ؓ了徏立一个公用数据库链接Q用如下显C的PUBLIC关键字:
CREATE PUBLIC DATABASE LINK GNIS
CONNECT TO GUEST IDENTIFIED BY WELCOME
USING 'GNIS';
即ɘq是一个公用链接,用户名仍旧固定。所有用这个链接的用户都作为用户GUESTq接到远E数据库?
使用数据库链接访问远E表
? 数据库链接GNISQ指明网l服务名Uͼ链接PROD事例到GNIS事例中的FEATURE_NAMES表?
权限c?/p>
当你建立一个数据库链接Ӟ关于你如何授权对q程数据库进行访问,有三U选择。这三种选择代表了数据库链接的另一U分cL法。这三种cd如下Q?
固定用户。ؓq程数据库链接指定用户名和口令,作ؓ数据库链接定义的一部分?
q接用户。在不指定用户名和口令时创徏的数据库链接?
当前用户。徏立数据库链接q指定CURRENT_USER关键字?
固定用户数据库链接是指在创徏链接时ؓq程数据库指定用户名和口令。这一链接不管什么时候用,也无使用Q都使用相同的用户名和口令登陆到q程数据库。到目前为止你在本文中所看到的都是固定用户链接?
固定用户链接Q尤其是公用固定用户链接的一个潜在问提是他们把远E系l上的同一帐户l了许多本地用户。从安全角度来说Q如果所有的本地用户在远E系l上拥有同一个帐P责Qp折中Q这取决于用L数量 。如果数据丢失,几乎不可能确定破坏是如何发生的。另一个潜在问题是公用固定用户链接对q程数据库的讉K权给了所有的本地数据库用戗?
如果你不惛_数据库链接中嵌入用户名和口oQOracle提供l你另一个非常有用的选择。你可以建立一个连接用户链接。连接用户链接是q样的链接,它通过M个正在用该链接的本地数据库的用L用户名和口o登陆到远E数据库。你可以通过单地I出用户名和口o来徏立一个连接用户链接。考虑如下定义Q?
CREATE PUBLIC DATABASE LINK GNIS
USING 'GNIS';
链接名是GNIS。它q接到远E数据库q接时用的|络服务名称是GNISQ但是没有指定用户名和口令。当你在查询中用这个链接时Q它向q程数据库发送你当前的用户名和口令。例如,如果你用AHMAD/SECRET 登陆C的本地数据库Q那么AHMAD/SECRET是你登陆到q程数据库时使用的用户名和口令?
Z使用一个连接用户链接,你必dq程数据库上有一个帐P了解q一Ҏ很重要的。不但这P而且你在两个数据库上应用同L用户和口令。如果本地登陆用AHMAD/SECRETQ那么登陆到q程数据库时也必M用同L用户名和口o。用连接用户链接时Q如果你的口令不同,你就无权登陆?
公用q接用户数据库链接尤其有用,因ؓ你可以徏立一个可被所有用戯问的链接Qƈ且所有用戯分别使用他或她自q用户名和口o授权。你获得责Q斚w的利益,没有远E数据库向你的本地数据库上的每一位用户开放。代h你必d两个数据库上建立用户帐户Qƈ且你必需信口o保持一致?
当前用户链接通过使用CURRENT_USER关键字徏立ƈ且与q接用户链接怼。只有当使用Oracle Advanced Security OptionQOracle高安全选项Q时Q你才能使用当前用户链接Q这个链接只Ҏ权用X.509认证的用h用?
׃n链接
׃n数据库链接是指该链接的多个用户可以共享同一个底层网l连接。例如,在有四位用户的MTSQ多U程服务器)环境下,每一个共享服务器q程都将与远E服务器有一个物理链接,q四位用户共享这两个链接?
表面上,׃n链接乍一听v来像是一件好事。在某些环境下的如此,但是Q当你考虑使用׃n链接Ӟ应当意识到这有许多局限性和警告Q?
如果你用一个专用的服务器连接来q接C的本地数据库Q链接只能在你从那些q接中创建的多重会话间共享?在MTS环境里,每一个共享服务器q程潜在地打开一个链接。所有的会话被同一׃n服务器进E提供ƈ且分享被那个q程打开的Q意共享链接。因为在MTS环境里的一个共享服务器q程能够服务于许多用戯接,׃n链接的用可能导致打开的链接远多于所必须的链接。用SHARED关键字徏立共享数据库链接。还必须使用AUTHENTICATED BY 子句在远E系l上指定一有效的用户名和口令。如下命令徏立一个共享的、公用的、连接用h据库链接Q?
CREATE SHARED PUBLIC DATABASE LINK GNIS
AUTHENTICATED BY DUMMY_USER IDENTIFIED BY SECRET
USING 'GNIS';
要获得创建链接和理分布式系l的更多资料Q请查阅Oracle Technology Network (http://otn.oracle.com/)?
使用AUTHENTICATED BY子句E微有些困扰Q但是由于实现共享链接的方式安全性决定它是必ȝ。这个例子中的用户名和口令DUMMY_USER/SECRET必须在远E系l上有效。然而,q程pȝ上用的帐户仍就是连接用L帐户。如果我以JEFF/SECRET登陆到我的本地数据库q用我刚徏好的׃n链接Q将会发生以下一pd事gQ?
Z打开链接QOracle使用DUMMY_USER/SECRET向远E数据库授权?然后QOracle试图使用HMAD/SECRET使我登陆到远E数据库。共享链接的主要目的是减两个数据库服务器之间的底层|络q接数量。它们最适合于MTS环境Q在那你拥有大量的通过q一链接讉Kq程数据库的用户。观念上Q你惌用户数量过׃n服务器进E的数量。那么你可以通过为每一׃n服务器进E打开一个链接而不是每位用h开一个链接的ҎQ节省资源?
查找关于数据库链接的资料
你可以从几个数据字典视图中获得徏立好的数据库链接的资料。DBA_DB_LINKS视图为每一定义的链接返回一行。OWNER 列和DB_LINK列分别显CZq一链接的所有者及名称。对公用数据库链接,OWNER列将包含'PUBLIC'。如果你建立固定用户链接Q用户名应在DBA_DB_LINKS视图的USERNAME列里Q但是口令只能从SYS.LINK$视图中看到。默认情况下Q只有具有SELECT ANY TABLEpȝ权限的DBA能够讉KSYS.LINK$视图查看口o。你应该保护讉K那个视图的权限。ALL_DB_LINKS 视图?USER_DB_LINKS视图?DBA_DB_LINKS视图相类?它们分别昄了你能够讉K的所有链接及你所拥有的全部链接。最后,V$DBLINK动态性能视图向你昄ZQ意给定时间你-当前用户Q打开的全部数据库链接?
全局性的数据库名U?
在分布式环境里,Oracle你的数据库链接名应与它们q接到的数据库的全局性名U相匚w。因此如果你正在q接到名UCؓGNIS.GENNICK.ORG的数据库Q你应当你的数据库链接命名为GNIS.GENNICK.ORG
为确定数据库的全局性名Uͼ以SYSTEM登陆q查询GLOBAL_NAME视图Q?
SQL> SELECT * FROM GLOBAL_NAME;
GLOBAL_NAME
_______________
GNIS.GENNICK.ORG
׃历史的原因,默认情况下,全局性名UC数据库链接名U的之间的链接不是强制性的。不q,你可以通过讄GLOBAL_NAMES的初始化参数为TRUE来改变这一行ؓ。例如:
SQL> SHOW PARAMETER GLOBAL_NAMES
NAME TYPE VALUE
________________________________________________________
global_names boolean TRUE
用于产生q个范例的事例要求你使用的数据库链接名,必须与目标数据库的全局性数据库名称相匹配。注意与一些Oracle文档中说的相反,关键是你的本C例的GLOBAL_NAMES讄。如果你的本C例中GLOBAL_NAMES=FALSEQ你p够用数据库链接Q而不用管它们是否与远E数据库的全局性名U相匚w。ȝ来说Q如果你讄GLOBAL_NAMES=TRUEQ你应该在你的所有事例中一律这么做?br />
create sequence dept_deptin_seq
increment by 10
start with 120
maxvalue 9999
nocache
nocycle
2) Confirming Sequences
verify your sequence values in the user_sequences data dictionary table
select sequence_name,min_value,max_value,increment_by,last_number
from user_sequences;
the last_number display the next available sequence number if nocache is specified
3)nextval and currval Pseudocolumns
--nextval return thee next available sequence value,it return a unique value every time
it si referenced,even for different ueer;
--currval obtains the current sequence value;
--nextval must be issued for that sequence before curval contains a value;
4) Using a Sequence
-- Caching sequence values in the memory give faster access to these values;
-- Gaps in sequence value can occur when
a rollback occurs
b the system crashes
c A sequence us used in another table;
5) alter sequence test increment by 10;
you can change all properties of the sequence except the start with .
6) remove sequence
drop sequence test;
2 index
1) how are indexes created
Automatically : a unique index is created automatically when you create primary key or
unique constraint in a table definition,
Manually: user can create nounique index on column to speed up access to the rows.
create index testindex on autoer(lanme);
2) When to Create an index
ypu should create an index if:
. a column contains a wide range of values
. a column contains a large number of null values
. one or more columns are frequently used together in where clause or a join condition;
. The table is large and most queries are expected to retrieve less than 2 to 4 percent
of the rows;
3) When not to create an index
this usually not worth creating an index if:
. the table is small
. The columns are not often used as a condition in the query.
. Most queries are expected to retrieve more than 2 to 4 percent of the rows in the
table
. the indexed columns are referenced as part of an expression.
4)Confirming indexes
. The user_indexes data dictionary view contains the name of the index and tis uniquess
. the user_ind_columns view contains the index name,the table name,and the column name.
select ic.index_name,ic_column_name,ic.column_position,ic_col_pos,ix.uniqueness
from user_indexed ix,user_ind_columns ic
where ic.index_name=ix.index_name
and ic.table_name='employees';
5)Z函数的烦?br /> . a function-based index is an index based on expressions
. The index expression is built form table columns,constraints,SQL functions and user-
defined functions
create index testindex2
on autors (upper(au_fname));
select * from authors
where upper(au_fname) like 'B%';
6) remoe index
drop index index_name;
3 synonyms
Simplify access to objects by creating a synonym
. Ease referring to a table ownerd by anther user
. Shorten lengthy object names;
create [publi] synonym synonym for object;
column name;
create or replace view empvu80
(id_number,name,sal,department_id)
as select employee_id,first_name||" "||last_name,salary.department_id
from employees
where department_id=80;
column aliases in the create view clause are listed in the same order as the columns in
the subquery
note : alter view_name is not a valid command.
4 Create a Complex View
Create a complex view that contains group functions to display values from two tables
create view dept_sum_vu
(name,minsal,maxsal,avgsal)
as
select d.department_name,min(e.salary),max(e.salary),avg(e.salary)
from employees e,departments d
where e.department_id=d.department_id
group by d.department_name;
5 Rules for performs DML operaton on a view
1) You can perform DML operation on simple views
2) You can not romove a row if the view contains the following:
--group functions
--a group by clause
--the distince keyword
-- rownum keyword
-- column defined by expressions
6 Using the with check option Clause
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.
creaate view test1
as
select * from emp where qty>10;
with check option;
update testview1 set qty=10
where ster_id=6830;
--when you doing the following update operation
update testview1 set qty=5 where id=10;
-- an error will report
--you violate the where clause
2)Any attempt to change the department number for any row in the view fails because it
violates the with check option constraint
create or replace view empvu20
as
select * where department_id=20
with check option constriant empvu20_ck;
7 Denying DML Operations
1 You can ensure that no dml operations occur by adding the with read only option to your
view definition.
2)Any attempt to a DML on any row in the view resuls in an oralce server error.
8 remove veiw
drop view_name
9 inline view
1) an inline view is a subquery with an alias that you can use within a sql statement.
2) a named subquery in the from clause of the main query is an exqmple of an inline view
3) an inline view is not a schema object.
10 Top-N Analysis
1)Top_N querise ask for the n largest or smallest values of a column.
2)Both largest values and smallest values sets considered Top-N queries
select * from (select ster_id,qty from sales);
example
To display the top three earner names and salaries from the employees
select rownum as rank,last_name,salary
from (select last_anme,slary from employee
order by slary desc)
where rownum<=3;
collection
delcare
type name_varray_type is varray(4) of varchar2(10);
name_array1 name_varray_type;
name_array2 name_varray_type;
begin
name_array1:=name_varray_type('scott','smith');
name_array2:=name_array_type('a','b','c');
name_array1:=name_array2;
end;
type name_array1_type is varray(4) of varchar2(10);
type name_array2_type is varray(4) of varchar2(10);
name_array1 name_array1_type;
name_array2 name_array2_type;
h相同的数据类型,单具有不同的集合cd不能构赋?br /> 2) l集合赋城null ?br /> 可以使用delete ?trim
也可以?I集合赋l目表集?br /> type name_varray_type is varray(4) of varchar2(10);
name_array name_varray_type;
name_empty name_varray_type;
name_array:=name_varray_type('1','2');
name_array:=name_empty;
3) 使用集合操作赋和比较集合都是10g 的内容,p176 先略q?br />4 扚wl定
执行单词sql 操作能传递所有集合元素的数据?br /> 1 forall 语句
用于insert update 和delete操作。在oracle9i 中forall 语句必须hq箋的元?br /> 1) using forall on insert
declare
type id_table_type is table of number(6)
index by binary_integer;
type name_table_type is table of varchar2(2)
index by binary integer;
id_table id_table_type;
name_table name_table_type;
begin
for i in 1..10 loop
id_table(i):=i;
name_table(i):='Name'||to_char(i);
end loop;
forall i in 1..id_table.count
insert into demo demo values(id_table(i),name_table(i));
end;
2)using forall on using update
forall i in 1..id_table.count
upate demo set name:=name_table(i)
where id:=id_table(i);
3)using forall on using delete
forall i in 1..id_table.count
delete from demo where id:=id_table(i);
4) using forall on part of the collection
for i in1..10 loop
id_table(i):=i;
name_table(i):="name"||to_char(i);
end loop;
forall i in 8..10 l
insert into demo values(id_table(i),name_table(i));
2 bulk collect
is fit for select into ,fetch into and dml clause
1) using bulk collect
declares
type emp_table_type is table of emp%rowtype
index by binary_integer;
emp_table emp_table_type;
begin
select * bulk collect into emp_table
from emp where deptno=&no;
for i in 1..emp_tablee.count loop
dbms_output.put_line(emp_table(i).ename);
end loop;
2) 在dml 的返回字句用bulk collect 字句
declare
type ename_table_type is table of emp.ename%type;
ename_table ename_table_type;
begin
deletee from emp where deptno=&no
returning ename bulk_collect into ename_table;
for i in 1..ename_table.count loop
dbms_output.put(ename_table(i));
end loop;
end;
end;
end;
parent table is deleted
on delete set null:Convert the dependent foreign key values to null when a row in the
parent table is deleted.
--parent table referenced table
--child table refernce other table
6 The check Constraint
Define a condition that each row must be satify
alter table test3
add constrain ch_test3 check(name like 's%')
7 Dropping a Constraint
1) Remove the manager constraint form the employee table
alter table test3
drop constriant test3_manager_fk
2) Remove the primary key constraint on the departments table and drop the associated
foreign key constraint on the employees.department_id column
alter table departments
drop primary key cascade
8 Disabling and enable Constraints
1)Execute the disable clause of the alter table statment to deactive an integrity
constraint
2)Apply the cascade option to disable dependent integrity constrints
alter table employees
disable constraint emp_emp_id_pl cascade
3) enabling Constraints
.Active an integrity constraint currently disabled in the table definition by using the
enable clause.
alter table employees
enable constraint emp_emp_id_pk;
a unique or a primary index is automatically created if you enable a unique key or a
primary key constraint
8 View Constraints
select constraint_name,constriant_type,serch_condition
from user_constraints
where table_name='employees'
9 view the columns associated with constraints
select constraint_name,column_name
from user_cons_columns
where table_name='employees'
select employee_id
from employees
where salary<all
(select salary
from employees
where job_id='ddd')
select emp.last_name
from employees emp
where emp.employee_id not in
(select mgr.manager_id
from employees mgr)
select last_namek,job_id,salary,
decode(job_id,'it' ,1*salary,
'manager',1.2*salary,
salary)
from employees
select count(*) from
select count(address) from authors
count the valid count of the address (exclude the null value)
2) Using theDISTINCT Keyword
count(distinct expr) return thee number of the distinct non-null value of the expr
select count(distincee department_id) from employees
3)Group functions and null values
group functions ignore null values in the clumn
4) Using thee NVL Function with Group Functions
The nul function force group funtion to include null values
select avg(nvl(commission_pct,0)) from employees
2 Creating Groups of Data
1)
a Divide rows in a table into smaller groups by using the group by clause
b All coulmns in the select list that are not in group function must be in the group by clause
select department_id,avg(salary)
from employees
group by department_id;
2) Grouping by More Than One Column
3) Ilegal Queries Using Group Functions
a You cannot use thee where clause to restrict groups
b You use thee having clause to restrict groups
c you cannot use group functions in the where clause
4)Excluding Group Resdults:The Having Clause
Use the HAVING clause to restrict groups
a Rows are grouped
b The group functions is applied
c Groups matcching the Having clause are display
select department_id,max(salary)
from employees
group by department_id
having max(salary)>10000
5) Nesting Group function
select max(avg(salary))
from employees
group by department_id;