oracle支援五種類型的完整性限制
not null (非空)--防止null值進入指定的列,在單列基礎上定義,預設情況下,oracle允許在任何列中有null值.
check (檢查)--檢查在限制中指定的條件是否得到了滿足.
unique (唯一)--保證在指定的列中沒有重複值.在該表中每一個值或者每一組值都将是唯一的.
primary key (主鍵)--用來唯一的辨別出表的每一行,并且防止出現null值,一個表隻能有一個主鍵限制.
poreign key (外部鍵)--通過使用公共列在表之間建立一種父子(parent-child)關系,在表上定義的外部鍵可以指向主鍵或者其他表的唯一鍵.oracle支援五種類型的完整性限制
poreign key (外部鍵)--通過使用公共列在表之間建立一種父子(parent-child)關系,在表上定義的外部鍵可以指向主鍵或者其他表的唯一鍵.
1--設定每行顯示多少字元 set linesize 300;
2 設定每頁顯示多少條記錄 set pagesize 30;
3 使用者名的切換: 如 conn system/tiger
conn sys/change_on_install as sysdba(注意超級使用者 在後面加as sysdba)
4 在超級使用者下查找普通使用者的表是查不到的 必須這樣查找 如 select * from scott.emp(普通使用者下的emp表)
5 檢視目前是那個使用者身份登入: show user;
6 檢視有多少張表: select * from tab;(注意不同使用者下的表是不同的)
7檢視表的結構: desc emp(emp為表名)
8 取出重複的列(distinct): 如 select distinct job emp(去掉job的重複的值)
9字元串的連結操作用: ||
10 查詢有獎金的員工: select* from emp where comm is not null;
11 查詢沒有獎金的員工資訊: select * from emp where comm is null;
12 兩個條件以上就得用and 如查詢工資大雨1500和有獎金的員工 select * from emp where sal>1500 and
comm is not null;
13 表示兩個條件有一個滿足就可就用:or 如查詢工資大于1500或者沒有獎金的員工資訊
select * from emp where sal>1500 or comm is not null;
14取反可以用not 如 查詢員工工資不大于1500和有獎金的員工資訊 如:
select * from emp where not (sal>1500 or comm is not null);
15 在什麼什麼之間用between----and----如查詢工資在1500和3000之間的員工資訊:
select * from emp where sal between 1500 and 3000;
16 查詢員工編号是2323, 4555, 2222的員工具體資訊: 如
select * from emp where empno in(2323,4555,2222);
17.l模糊查詢 like 一般結合"%"和"_"使用其中%:表示可以比對任意長度的内容,"_"表示比對一個長度放入内容 如: 查詢員工姓名中第二哥字母是m的員工資訊:
select * from emp where ename like '_m%';
又如姓名中包含m的員工 select * from emp where ename like '%m%';
18oracle中不等于有兩種表示方式"<>"和"!="
19 排序用order by {asc desc}其中asc 是升序排列 如果不寫就預設按升序排列desc是按降序排列 排序語句放在sal語句的最後如: 按員工工資進行排序
select * from emp order by sal asc(升序)
selecct * from emp order by sal desc(降序)
select * from emp where deptno='10' order by sal desc,hiredate asc;(查詢部門10的員工工資的升序排列如果工資相等就按員工的入職時間排序)
20.group by 用于對查詢的結果進行分組統計: 顯示每個部門的平均工資和最高工資 如:
select avg(sal),max(sal) from emp group by deptno;
having 子句用于限制分組顯示結果: 顯示平均工資大于2000的的部門号和他的平均工資?
如:select avg(sal), deptno from emp group by deptno having avg(sal)>2000;
2. 單行函數:
1 小寫變大寫: upper 如 select * from emp where ename=upper('smith');
講一個字元串變為小寫字母表示 如: select lower('hello world') from dual;
将單詞的首字母變大寫 用 initcap 如: select initcap('hello world') from dual;
2.字元串的操作
substr()截取字元串 length()字元串的長度 replace()替換字元串
3數值函數
四舍五入: round();
截斷小數位:trunc();
一.入門部分
1. 建立表空間
create tablespace schooltbs datafile ‘d:\oracle\datasource\schooltbs.dbf’ size 10m autoextend on;
2. 删除表空間
drop tablespace schooltbs[including contents and datafiles];
3. 查詢表空間基本資訊
select *||tablespace_name from dba_tablespaces;
4. 建立使用者
create user lihua
identified by lihua
default tablespace schooltbs
temporary tablespace temp;
5. 更改使用者
alter user lihua
identified by 123
default tablespace users;
6. 鎖定使用者
alter user lihua account lock|unlock;
7. 删除使用者
drop user lihua cascade;--删除使用者模式
8. oracle資料庫中的角色
connect,dba,select_catalog_role,delete_catalog_role,execute_catalog_role,exp_full_database,imp_full_database,resource
9. 授予連接配接伺服器的角色
grant connect to lihua;
10.授予使用表空間的角色
grant resource to lihua with grant option;--該使用者也有授權的權限
11.授予操作表的權限
grant select,insert on user_tbl to scott;--目前使用者
grant delete,update on lihua.user_tbl to scott;--系統管理者
12.修改表的結構(alter)
alter table 表名 add(列的名稱,列的類型);
二.sql查詢和sql函數
1.sql支援的指令:
資料定義語言(ddl):create,alter,drop
資料操縱語言(dml):insert,delete,update,select
資料控制語言(dcl):grant,revoke
事務控制語言(tcl):commit,savepoint,rollback
2.oracle資料類型
字元,數值,日期,raw,lob
字元型
char:1-2000位元組的定長字元
varchar2:1-4000位元組的變長字元
long:2gb的變長字元
注意:一個表中最多可有一列為long型
long列不能定義唯一限制或主鍵限制
long列上不能建立索引
過程或存儲過程不能接受long類型的參數。
數值型
number:最高精度38位
日期時間型
date:精确到ss
timestamp:秒值精确到小數點後6位
函數
sysdate,systimestamp傳回系統目前日期,時間和時區。
更改時間的顯示
alter session set nls_date_language=’american’;
alter session set nls_date_format=’yyyy-mm-dd’;
oracle中的僞列
像一個表列,但沒有存儲在表中
僞列可以查詢,但不能插入、更新和修改它們的值
常用的僞列:rowid和rownum
rowid:表中行的存儲位址,可唯一标示資料庫中的某一行,可以使用該列快速定位表中的行。
rownum:查詢傳回結果集中的行的序号,可以使用它來限制查詢傳回的行數。
3.資料定義語言
用于操作表的指令
create table
alter table
truncate table
drop table
修改表的指令
alter table stu_table rename to stu_tbl;--修改表名
alter table stu_tbl rename column stu_sex to sex;--修改列名
alter table stu_tbl add (stu_age number);--添加新列
alter table stu_tbl drop(sex);--删除列
alter table stu_tbl modify(stu_sex varchar2(2));--更改列的資料類型
alter table stu_tbl add constraint pk_stu_tbl primary key(id);--添加限制
4.資料操縱語言
select,update,delete,insert
利用現有的表建立表
create table stu_tbl_log as select id,stu_name,stu_age from stu_tbl;--
選擇無重複的行
select distinct stu_name from stu_tbl;--
插入來自其他表中的記錄
insert into stu_tbl_log select id,stu_name,stu_age from stu_tbl;
5.資料控制語言
grant,revoke
6.事務控制語言
commit,savepoint,rollback
7.sql操作符
算術操作符:l+-*/
比較操作符:l=,!=,<>,>,<,>=,<=,between-and,in,like,is null等
邏輯操作符:land,or,not
集合操作符:lunion,union all,intersect,minus
連接配接操作符:l||
示例中stu_tbl_log中的資料如下:
id stu_name stu_age
---------- -------------------- ----------
1000 李華 20
1001 accp 20
1003 nimda 3
stu_tbl中的資料如下:
id stu_name st stu_age
---------- -------------------- -- ----------
1000 李華 男 20
1001 accp 男 20
1002 admin 男 30
示例:
select (3+2)/2 from dual;--算術操作符,結果:2.5
select * from stu_tbl where stu_age>=20;--比較操作符
select * from stu_tbl where stu_name like '%a%';--比較操作符:like
select * from stu_tbl where stu_name like 'a___';--比較操作符:like
select * from stu_tbl where stu_age in(20,30);--比較操作符:in
select * from stu_tbl where stu_age between 20 and 30;--比較操作符:between
select stu_name from stu_tbl union all
select stu_name from stu_tbl_log;--集合操作符:union all,測試結果具體如下:
stu_name
-----------
李華
accp
admin
nimda
已選擇6行。
select stu_name from stu_tbl union
select stu_name from stu_tbl_log;--集合操作符:union,測試結果具體如下:
---------
select stu_name from stu_tbl intersect
select stu_name from stu_tbl_log;--集合操作符:intersect,測試結具體如下:
----------
select stu_name from stu_tbl minus
select stu_name from stu_tbl_log;--集合操作符:minus,測試結果如下:
從中可以看出:
minus是擷取第一張表獨有的資料
intersect是擷取兩張表中都有的資料
union是整合兩張表的資料,都有的隻顯示一次
union all是純粹的兩張表資料整合
select id,stu_name||' '||stu_sex as name_sex,stu_age
from stu_tbl;--連接配接操作符||,測試結果具體如下:
id name_sex stu_age
---------- ----------------------- ----------
1000 李華 男 20
1001 accp 男 20
1002 admin 男 30
8.sql函數
單行函數:從表中查詢的每一行隻傳回一個值,可出現在select子句,where子句中
日期函數
數字函數
字元函數
轉換函數:tochar(),todate(),tonumber()
其他函數:
nvl(exp1,exp2):表達式一為null時,傳回表達式二
nvl2(exp1,exp2,exp3):表達式一為null時傳回表達式三,否則傳回表達式二
nullif(exp1,exp2):兩表達式相等時,傳回null,否則傳回表達式一
分組函數:基于一組行來傳回
avg,min,max,sum,count
group by,having
分析函數
row_number,rank,dense_rank
select u.user_name,sum(oi.order_num*oi.order_price) as total,row_number() over (order by sum(oi.order_num*oi.order_price) desc) as sort from order_item_tbl
oi,user_tbl u,order_tbl o where oi.order_id = o.id and o.user_id = u.id group by u.user_name;
三.鎖和資料庫對象
1.鎖:資料庫用來控制共享資源并發通路的機制。
鎖的類型:行級鎖,表級鎖
行級鎖:對正在被修改的行進行鎖定。行級鎖也被稱之為排他鎖。
在使用下列語句時,oracle會自動應用行級鎖:
insert,update,delete,select…… for update
select……for update允許使用者一次鎖定多條記錄進行更新。
使用commit or rollback釋放鎖。
表級鎖:
lock table user_tbl in mode mode;
表級鎖類型:
行共享 row share
行排他 row exclusive
共享 share
共享行排他 share row exclusive
排他 exclusive
死鎖:兩個或兩個以上的事務互相等待對方釋放資源,進而形成死鎖
2.資料庫對象
oracle資料庫對象又稱模式對象
資料庫對象是邏輯結構的集合,最基本的資料庫對象是表
資料庫對象:
表,序列,視圖,索引
序列
用于生成唯一,連續序号的對象。
建立文法:
create sequence user_id_seq
start with 1000
increment by 1
maxvalue 2000
minvalue 1000
nocycle
cache 1000;--指定記憶體中預先配置設定的序号
通路序列:
select user_id_seq.currval from dual;
select user_id-seq.nextval from dual;
更改删除序列:
alter sequence user_id_seq maxvalue 10000;--不能修改其start with 值
drop sequence user_id_seq;
在hibernate中通路序列:
user_id_seq
視圖
以經過定制的方式顯示來自一個或多個表的資料
建立視圖:
create or replace view
user_tbl_view (vid,vname,vage)
as select id,user_name,age from user_tbl
[with check option]|[with read only];
建立帶有錯誤的視圖:
create force view user_tbl_force_view as
select * from user_table;--此時user_table可以不存在
建立外聯接視圖:
create view user_stu_view as
select u.id,u.user_name,u.password,s.ddress
from user_tbl u,stu_tbl s
where u.s_id(+)=s.id;--哪一方帶有(+),哪一方就是次要的
删除視圖:
drop user_stu_view;
索引
用于提高sql語句執行的性能
索引類型:
唯一索引,位圖索引,組合索引,基于函數的索引,反向鍵索引
建立标準索引:
create index user_id_index on user_tbl(id) tablespace schooltbs;
重建索引:
alter index user_id_index rebuild;
删除索引:
drop index user_id_index;
建立唯一索引:
create unique index user_id_index on user_tbl(id);
建立組合索引:
create index name_pass_index on user_tbl(user_name,password);
建立反向鍵索引:
create index user_id_index on user_tbl(id) reverse;
四.使用pl/sql
可用于建立存儲過程,觸發器,程式包,給sql語句的執行添加程式邏輯。
支援sql,在pl/sql中可以使用:
資料操縱指令
事務控制指令
遊标控制
sql函數和sql運算符
支援面向對象程式設計(oop)
可移植性
更佳的性能,pl/sql經過編譯執行
分為三個部分:聲明部分,可執行部分和異常處理部分
[declare
declarations]
begin
executable statements
[exception
handlers]
end;
打開輸出
set serverout on;
--根據輸入編号擷取某學員的成績--if
declare
score user_tbl.score%type;
select score into score from user_tbl where id='&id';
if score>90 then
dbms_output.put_line('優秀');
elsif score>80 then
dbms_output.put_line('良好');
elsif score>60 then
dbms_output.put_line('及格');
else
dbms_output.put_line('差');
end if;
--根據學員姓名擷取某學員的成績--if
select score into score from user_tbl where user_name='&name';
--case的使用
grade user_tbl.grade%type;
select grade into grade from user_tbl where id='&id';
case grade
when 'a' then dbms_output.put_line('優異');
when 'b' then dbms_output.put_line('優秀');
when 'c' then dbms_output.put_line('良好');
else dbms_output.put_line('一般');
end case;
--基本循環
i number(4):=1;
loop
dbms_output.put_line('loop size:'||i);
i:=i+1;
exit when i>10;
end loop;
--while循環
while i<=10 loop
dbms_output.put_line('while loop size='||i);
--for循環
for i in 1..10 loop
dbms_output.put_line('for loop size:'||i);
i number(2):=1;
j number(2):=1;
for i in reverse 1..9 loop
for j in 1..i loop
dbms_output.put(j||'x'||i||'='||j*i||' ');
dbms_output.put_line('');
--動态sql
userid number(2);
sql_str varchar2(100);
username user_tbl.user_name%type;
execute immediate 'create table testexe(id number,test_name varchar2(20))';
userid:='&userid';
sql_str:='select user_name from user_tbl where id=:id';
execute immediate sql_str into username using userid;
dbms_output.put_line(username);
(or
id_param number:='&id_param';
sql_str varchar2(100);
name_param stu_tbl.stu_name%type;
begin
sql_str:='select stu_name from stu_tbl where id=:p';
execute immediate sql_str into name_param using id_param;
dbms_output.put_line(name_param);
end;
/
)
--異常處理
grade number(4);
grade:='&grade';
when 1 then dbms_output.put_line('好的');
--else dbms_output.put_line('不好');
exception
when case_not_found then
dbms_output.put_line('輸入類型不比對!');
--系統異常
rowd user_tbl%rowtype;
select * into rowd from user_tbl;
dbms_output.put_line(rowd.id||''||rowd.user_name||' '||rowd.password);
when too_many_rows then
dbms_output.put_line('不能将多行賦予一個屬性!');
or
select * into rowd from user_tbl where id=5;
dbms_output.put_line(rowd.id||' '||rowd.user_name||' '||rowd.password);
when no_data_found then
dbms_output.put_line('沒有您要查找的資料!');
--自定義錯誤
invaliderror exception;
category varchar2(20);
category:='&category';
if category not in('附件','頂盤','備件') then
raise invaliderror;
dbms_output.put_line('您輸入的類别是:'||category);
when invaliderror then
dbms_output.put_line('無法識别的類别!');
--引發應用程式異常
app_exception exception;
select grade into grade from user_tbl where id=&id;
if grade='a' then
raise app_exception;
dbms_output.put_line('查詢的等級為:'||grade);
when app_exception then
raise_application_error(-20001,'未知的等級!');
五、遊标管理
遊标類型:隐式遊标,顯式遊标,ref遊标
ref遊标用于處理運作時才能确定的動态sql查詢的結果
==========隐式遊标==========
在pl/sql中使用dml語句時自動建立隐式遊标
隐式遊标自動聲明、打開和關閉,其名為sql
隐式遊标的屬性:
%found sql語句影響實質後傳回true
%notfound sql語句沒有影響實質後傳回true
%rowcount sql語句影響的行數
%isopen 遊标是否打開,始終為false
update user_tbl set score=score+5;
if sql%found then
dbms_output.put_line('資料被更改: '||sql%rowcount);
elsif sql%notfound then
dbms_output.put_line('沒有找到資料!');
if sql%isopen then
dbms_output.put_line('open');
dbms_output.put_line('close');
==========顯式遊标==========
在pl/sql的聲明部分定義查詢,該查詢可以傳回多行
j 聲明遊标
j 打開遊标
j 從遊标中取回資料
j 關閉遊标
聲明遊标完成兩個任務:
給遊标命名
将一個查詢與遊标關聯
cursor cursor_name is select statement;
打開遊标:
open cursor_name;
取資料:
fetch cursor_name into record_list;
關閉遊标:
close cursor_name;
顯式遊标的屬性:
%found 執行最後一條fetch語句成功傳回行時為true
%notfound 執行最後一條fetch語句未能傳回行時為true
%rowcount 傳回到目前為止遊标提取的行數
%isopen 遊标是否打開
users user_tbl%rowtype;
cursor boys_cur is select * from user_tbl where sex='h';
open boys_cur;
fetch boys_cur into users;
exit when boys_cur%notfound;
dbms_output.put_line(users.user_name||' '||users.password);
dbms_output.put_line(boys_cur%rowcount);
close boys_cur;
帶參的顯式遊标
cursor boys_cur(sexparam varchar2)
is select * from user_tbl where sex=sexparam;
open boys_cur('&sex');
使用顯式遊标更新行
cursor user_update_cur is select sex from user_tbl for update;
usersex user_tbl.sex%type;
open user_update_cur;
fetch user_update_cur into usersex;
exit when user_update_cur%notfound;
dbms_output.put_line(usersex);
if usersex = 'm' then
update user_tbl set score=score-5 where current of user_update_cur;
update user_tbl set score=score+5 where current of user_update_cur;
close user_update_cur;
commit;
循環遊标
cursor user_cur is select * from user_tbl;
for username in user_cur loop
dbms_output.put_line(username.user_name||' '||username.sex);
==========ref遊标==========
ref遊标和遊标變量用于處理運作時動态執行的sql查詢
建立遊标變量的步驟:
j 聲明ref遊标類型
j 聲明ref遊标類型的變量
聲明類型的文法
type ref_cursor_name is ref cursor [return return_type];
打開遊标變量的文法
open cursor_name for select_statement;
----聲明強類型的遊标
type ref_cur is ref cursor return user_tbl%rowtype;
users_cur ref_cur;
----聲明弱類型的遊标
type ref_cur is ref cursor;
示例
----強類型
open users_cur for select * from user_tbl where user_name='ny2t92';
fetch users_cur into users;
exit when users_cur%notfound;
dbms_output.put_line(users.user_name);
close users_cur;
----弱類型
my_cur ref_cur;
stus stu_tbl%rowtype;
open my_cur for select * from user_tbl;
fetch my_cur into users;
exit when my_cur%notfound;
close my_cur;
open my_cur for select * from user_tbl where user_name='ny2t92';
open my_cur for select * from stu_tbl;
fetch my_cur into stus;
exit when my_cur%notfound;
dbms_output.put_line(stus.stu_name);
----動态sql遊标
username varchar2(20);
sqlstmt varchar2(200);
username:='&username';
sqlstmt := 'select * from user_tbl where user_name= :name';
open my_cur for sqlstmt using username;
六.子程式
子程式分為:存儲過程和函數,它是命名的pl/sql塊,編譯并存儲在資料庫中。
子程式的各個部分:聲明部分,可執行部分,異常處理部分。
過程----執行某些操作
函數----執行操作并傳回值
==========存儲過程==========
建立過程的文法:
create or replace procedure
proce_name (parameter_list)
is|as
local variable declaration
exception_handlers
end proce_name;
過程參數的三種模式:
in----用于接收調用的值,預設的參數模式
out----用于向調用程式傳回值
in out----用于接收調用程式的值,并向調用程式傳回更新的值
執行過程的文法:
execute proce_name(parameter_list);
或
variable var_list;
proce_name(var_list);
将過程執行的權限授予其他使用者:
grant execute on proce_name to scott;
grant execute on proce_name to public;
删除存儲過程:
drop procedure proce_name;
==========函數==========
建立函數的文法:
create or replace function
fun_name (parameter_list)
return datatype is|as
local declarations
executable statements;
return result;
exce_handlers;
函數隻能接收in參數,不能接受out或in out參數,形參不能是pl/sql類型
函數的傳回類型也必須是資料庫類型
通路函數的方式:
j 使用pl/sql塊
j 使用sql語句
select fun_name(parameter_list) from dual;