Oracle基本語法

select a.uiblockid,a.uilac_id,cast(a.subsum*1.0/b.totalsum as numeric (10, 2) ) BL from
(select sum(uinmsg_lac) subsum,uilac_id,uiblockid from
T_msg_lac group by uilac_id,uiblockid) a,
(select sum(uinmsg_block_all) totalsum,uiblockid from T_msg_lac
group by uiblockid) b
where a.uiblockid=b.uiblockidsql

清空回收站數據庫

PURGE recyclebin;數組

建立用戶
 
CREATE USER "CEMDB" PROFILE "DEFAULT" IDENTIFIED BY "*******" DEFAULT TABLESPACE "USERS" TEMPORARY TABLESPACE "TEMP" ACCOUNT UNLOCK
GRANT "CONNECT" TO "CEMDB"session

alter session set NLS_date_format='YYYY-MM-DD';   修改數據查詢時間格式ide

create sequence NumSeq increment by 1 start with 1 maxvalue 999;  建立序列 函數

insert into table values(NumSeq.nextval);   表中插入序列oop

select NumSeq.currval from dual;  查詢序列當前值;ui

drop sequence NumSeq  ; 刪除序列;rest

Create or replace type 類型名 as object
(
    colum1 varchar(20),
    colum2 varchar(30)
)  建立類型orm

Create table tableObject
(
  Colum1 char(10),
  Colum2 類型名
) 建立代類型的表

Insert into tableobject values('aaa',類型名('a','b'));  想自定義類型表中添加記錄


select s.Colum1,s.Colum2.colum1,s.Colum2.Colum2 from tableObject s 查詢自定義類型表記錄

create or replace type person  as object
(
  personName varchar(10),
  personSex varchar(2),
  PessonBirth date
) not final;   建立可擴展的類型

create or replace Type studentType under person
(
  StudentNo int,
  StudentScore int
)   此類型繼承了 Person類型. 也就是 studentType類型中已經有了 Person類型的三個屬性.

create table student of StudentType; 建立具備StudentType的表
類型中不能保存數據.只有在建立此類型的表才能夠存儲數據.

insert into student values('a','b',to_date(1980-1-1','YYYY-MM-DD'),1001,89)); 向此關係類型的表中添加數據.

select *  from student 對具備此類型的表進行查詢.

update student a set a.personsex='女' where personname='a'; 更新此類型的表中的數據.

insert into student select studenttype('a','b',to_date(1980-1-1','YYYY-MM-DD'),1001,89)) from student where personName='a'; 建立抽象類型的面向對象表

updata student set studenttype('a','b',to_date(1980-1-1','YYYY-MM-DD'),1001,89)) where provid='10001'; 對錶中的整個對象進行更新.

建立代方法的對象類型
create or replace type studenttype as object
(
  stuid varchar(10),
  stuName varchar(10),
  HomAddress Address,
  Member funcation getAddress Return Address,
  Member procedure setAddress(newAddress Address)
);
 
create or replace type body studenttype as
Member function getAddress return Address is
begin 
   Return HomeAddress;
end;
Member procedure setAddress(newAddress Address) is
begin
  HomeAddress:=newAddress;
end;
end;


一建立帶有可變數組的表
A
---格式 create or replace type 基類型名 as object (字段清單)

--實例
create or replace type MingXiType as object
(
  goodsid varchar(15),
  InCount int,
  ProviderID varchar(10)
)
B.創建嵌套項類型的可變數組
格式:Create or replace 可變數組類型名 as Varray(最大行數) of 可變數組的基類型;
實例: Create Or Replace Type arrMingXiType as varray(100) of MingXiType;
C.建立一個主表
Create table inStockOrder
(
  OrderID varchar(15) Not Null Primary Key,
  InDate Date,
  OperatorId varchar(10),
  Mingxi arrMingXiType
);
2.操做可變數組

A.插入數據
  Insert into InStockorder
  Values('20020807001',To_data(2002-08-07','YYYY-MM-DD'),'002',
   aarrMingXiType(MingXiType('S001',100,'100009),
   MingXiType('S001',100,'100009)))

b.查詢數據
使用普通的select不能顯示Varray中的數據.要使用帶有遊標的PL/SQL塊來操縱Varray.
但可使用Table()函數查詢集合列
select * from Table(select t.Mingxt from instockorder t where t.orderid='20020807001')

c.修改數據
實例:把編號爲20020807001的入庫單的貨物編號爲S001的入庫數量改成200
Update instockorder
set MingXi=arrMingXiType(MingXiType('S001',200,'10009'),MingXiType('T002',400,'10003')) where orderID='200208070001'
注意: 不能更新VArray中的單個元素,必須更新整個的Varray.

建立嵌套表
A 建立嵌套表基類型
格式: Create or replace type 嵌套表基類型名 as object
實例: Create or replace type MingXiType As Object
      (
           GoodsId varchar(15),
           InCount int,
           ProviderID varchar(10)
       ) not final;
B.建立嵌套表類型
格式: Create Type 嵌套表類型名 As Table of 類型名;
實例: Create Or Type nestMingXiType As Tabele of MingXiType;
C.建立主表,其中一個列是嵌套表的類型的
格式:  Create Table 表名
       (
           字段1  類型及長度.....字段N  類型及長度,
           嵌套類型字段  嵌套表類型名
        )
        Nested Table 嵌套類型字段名 Store As 真正存儲的嵌套表;
實例:(建立入庫表)
Create Table InStockTable
(
   OrderID varchar(13) not null Primary Key,
   InDate Date,
   Operator varchar(12),
   MingXi nestMingXiType
) Nested Table MingXi Store As MingxiTable;
2.操縱嵌套表
A.向嵌套中插入記錄
格式: Insert Into 主表名[(字段列表)]
      Values(主表字段1值,.....主表字段N的值,
             嵌套表類型名(嵌套表類型的基類型名(屬性1的值,....屬性N的值)
             )
      );
實例: Insert Into InStockTable
      Values('200208060001',To_Date('2002-08-06','YYYY-MM-DD'),'3001',
      nestMingXitableType(MingXiType('J0001',200,'1001'),
                      MingXiType('S0001',1000,'1002'),
                      MingXiType('T0005',500,'1003')
                     )
             )
B.更新嵌套表中的數據
Update Table(select t.mingxi from  instocktable t where orderid='200208060001') mx
set mx.incount=500
where mx.goodsid='j0001';
c.刪除嵌套中的數據
  delete from
  table (select t.mingxi from instocktable t where orderid='200208060001') t
  where t.goodsid='10001'
建立對象表
Create Table ObjectTable1  of MingxiType;
插入對象記錄
Insert into objectTable1 values('3002',3000,'s001');
查詢對象表中的OID
select ref(a) from objecttable1 a;

1.Ref 函數使用
--建立科室類型
Create or replace Type officeType As Object
(
  ID varchar(10),
  TypeName varchar(10)
);
--建立對應的對象表-- 科室表
Create table office of  officeType;
--向對象表中插入記錄
 Insert into office Values('0001','財務科');
 Insert into office Values('0002','人士科');
 Insert into office Values('0003','伙食科');
 Insert into office Values('0004','後勤科');

--使用Ref函數查看行對象的OID值以及表中的科室編號,名次
  格式:select Ref(表別名) From 對象表  對象表的別名;
  實例:
       select Ref(f) ,ID,TypeName from Office f;   -- 將表的別名做爲輸入
  結果: 對象的OID編號, 類型名

2.Ref類型
  Ref類型的使用:經過REf和DEref運算符,能夠將OID用於建立外鍵關係.
--建立具備外鍵的關係表--人事表
  Create Table Worker
(  WorkerID varchar(10) primary key,
   WorkerName varchar(10),
   Workeroffice ref officeType Scope Is Office,  --引用officetype外鍵.關聯的是OID值
   phone varchar(16)
);

--向表中插入數據,此表將從上面建立的對象表中引用數據
Insert into worker select 'C001','張小明',Ref(0),'010-1234567' from office 0
where ID='001'
3.使用Deref查看OID指向的行中的數據
 格式: select Deref(表別名.引用類型列名) from 表名  表的別名
 實例: select workerID,workerName,DeRef(w.workerOffice),phone from worker w
       where workerID='C001'
4.Value函數;
--使用value()返回表中的對象
  select Value(0) from office 0;
5.對象試圖
  Create view officeview of officetype with object oid(id)
  as select * from  office;
6.建立對象試圖
  A.建立基於關係表父表的對象類型.
  create or replace type depttype as object
  (
     deptno number(2),
     dName varchar2(14),
     loc varchar(13)
);
--建立基於關係表的視圖(dept)
  create view deptview of depttype with object oid(deptno) as select * from dept;
B.建立引用視圖(相似於關係建立一個從表)
  Create view emp_view as select make_ref(deptview,deptno) deptOid,empno,ename from emp;
--對象視圖其實是將關係包裝成對象表,經過構造關係表每條記錄OID來實現相似於關係表 --主外鍵約束.

三.動態遊標

declare
  type refEmpcur is ref cursor;
  empcur refempcur
  Emprow emp%rowtype;
  flag  int:=0;
begin
  flage:=&flage;
  if flag=0 then
     Open Empcur for select * from emp where sal>500 and sal<1000;
  elseif flag=1 then
     open Empcur for select * from emp where sal>=1000;
  else
     open Empcur for select * from emp;
  end if;
  /* 因爲For循環會自動的打開遊標,因此REF遊標不能使用
   for Emprow int  Empcur loop
    DBMS_output.put_line('empno'||emprow.empno);
   end loop;  */
  loop
      Fetch empcur into emprow;    
      DBMS_output.put_line('empno'||emprow.empno);
      wxit when empcur%notfound;
  end loop;
  
end;

過程的使用
A.結構
--說明部分
Create or replace  procedure 過程名
as
/* 聲明部分*/
begin
  /*聲明部分*/
exception
  /*異常處理部分*/
end [過程名];
//注:(過程是有名的程序塊,as代替了Declare聲明關鍵詞)
B.格式
Create or replace procedure 過程名
[(參數1 in|out|in out 類型,參數2 in|out| int out 類型,.....參數N in|out|in out 類型)]
{is|as}
過程體

四.程序包
A.包說明及主體
格式:Create [or Replace] package 包名 IS|AS
    變量聲明|類型定義|異常聲明|遊標聲明|函數說明|過程說明
Pragma restrict_references(函數名,WNDS[,WNPS][,RNDS][,RNDS])
           end [包名];
B.格式:
Create  [or replace] package body 包名 IS|AS
/*包體名必定要已經定義的包名同*/
變量聲明|類型定義|異常聲明|遊標聲明|函數定義|過程定義
end [包體名];
C.包調用
  包名.類型名;
  包名.函數名[參數表];
  包名..過程名[參數表];

  顯示綁定到引用遊標變量上的值----包調用
  set Autoprint on
  1.variable tempCursor;
  2.exec Studentpackage.returnstudent(:tempCur);
D.數據字典
  User Objects ,User_source
F.包的修改和刪除
  Drop Package [body] 包名;
  Drop Package Body StudetPackage;


包的實例:
包的聲明部分
Create or replace package Studentpackage
is
   type curRefstudent is ref Cursor return student%rowtype;
   Procedure selectstudent(findID in strudent.stuid%type)
   Procedure Insertstudent(Newstudent in student%type);
   Procedure Updatestudent(Newstrdeng in student%rowtype);
   procedure deletestudent(DelID in student.stuid%Type);
   Procedure Returnstudent(inOutstu in out Currefstudeng);
   function ReturnRecordCount return Number;
end strudentpackage;
建立包的主體部分實例:
Create or replace Package body studentPackage as
  procedure selectstudent(findID in student.stuid%type) as
     Cursor findcur is select * from student where stuid=findid;
  begin
     for s in findcur loop
        DBMS_output.put_line(s.stuid||' '||s.stuName||' '||s.sex);
     end loop;
  Exception
     when No_date_found then
        DBMS_output.put_Line('沒有查到ID爲'||findid||'的記錄!');
     when others then
        DBMS_OutPut.put_Line('查詢過程當中發生意外狀況');
  end selectstudent;

  Procedure Insertstudent(newstudent in student%RowType) AS
     iRec Integer;
     Not_Exits_student Exception;
  begin
     select count(*) into iRec from Student where stuid=newstudent.stuid;
     if iRec>0 then
        Raise not_exists_studeng;
     else
        Insert into Studeng valuew(newStudeng.stuid,newstudeng.stuName,newstudeng.sex);
        commit;
     end if;
   Exception
     when Not_Exists_Studeng Then
        DBMS_Output.put_line('要插入的編號爲:'||NewStudent.stuid||'的記錄已經存在');\
     when others then
        DBMS_OUtput.put_Line('插入記錄操縱過程當中出現錯誤');
   end InsertStudent;
............................... --中間其餘存儲過程的實現 省略
//引用遊標的使用.
  Procedure Returnstudent(inOutStu in out curRefStudent) as
  begin
       Open inOutStu For select * from student;
  end Returnstudent;

end  studentPackage ;

程序包的調用
1.調用Studentpackage中的InsertStudent過程
  Declare
    newStu  Student%RowType;
  begin
     Newstu.stuid:='1001';
     newstu.stuName:='馬大哈';
     Studentpackage.insertstudent(newstu);
  end;
2.
  Declare
     newStu Student%RowType;
  begin
    newstu.stuid:='1001';
    newstu.stuname:='李連杰';
    newstu.sex:='男';
    Studentpackage.Updatestudent(newstu);
  Exception
    when Dup_Val_On_Index then
      DBMS_OUTPUT.put_Line('惟一約束被破壞');
    when Others then
      DBMS_OUTPUT.PUT_Line('更新過程出現錯誤');
  end;
3.
  begin
     StudentPackage.DeleteStudent('888');
  end;
4.
  begin
    DBMS_OUTPUT.PUT_line(StudentPackage.ReturnRecordCount);
  end;
5.調用引用遊標
  set Autoprint on
  Variable tempcur refcursor;
  exec Studentpackage.returnstudent(:tempcur);
 
函數級別的使用
Create table test(a int);

Create or replace package Mypack
is
   procedure UpdateTable(s Int);
   Pragma restrict_references(Updatetable,Wnds);
end Mypack;

Create or replace package body Mypack
is
  procedure Updatetable(s Int) is
  begin
    Update test set a=s;
  end;
end;

觸發器的使用:
1.觸發器具備三個部分
  (1)觸發事件
  (2)可選的觸發器約束條件;
  (3)觸發器動做
2.能夠建立對應以下語句所觸發的觸發器;
  (1)DML語句(Insert Delete UPdate);
  (2)DDL語句(create Alter Drop)
  (3)數據庫操縱(serverError  logon  logoff   Startup   Shutdown)
3.可建立觸發器的對象  
  (1) 數據庫表
  (2)數據庫視圖
  (3)用戶模式
  (4)數據庫實例
4.觸發器類型
  (1) DML觸發器
  (2)系統觸發器
  (3)替代(Instead of) 觸發器
5.執行DML語句的順序
  (1)執行Before語句級觸發器(若是有);
  (2)對於受語句影響的每一行,執行DML語句;
  (3)執行After語句級觸發器(若是有)
6.兩個特殊值  :New 新值  :Old舊值

7.觸發器謂詞
  (1)  Inserting
  (2)  Updating
  (3)  Deleting

二,建立DML觸發器
  Create [or Replace] Trigger [模式.]觸發器名
  before | After  Insert| Delete |Update Of 列名
   on 表名
  [For Each Row]
  when
     pl/sql 塊

1.使用Before觸發器(new)
Create or replace Trigger tg_student
before insert on Student
for each row
when (new.sex='f')

(一)PL/SQL索引表
一PL/SQL表
1.定義表類型
Type 表類型名 Is Table of 列類型 | 變量數據類型[非空] index By Binary_Integer;
注:
A 表類型名: 是表類型定義的名稱(像記錄類型同樣)
B列類型:能夠是char,Date,Number等任何標量的數據類型
C變量數據類型: 能夠是%Type或%Rowtype,Record等類型

實例:
Type stuNametableType is Table of varchar(10) index By Binary_Integer;
Type StudentTableType is Table of Student%RowType  Index By Binary_Integer;

2.聲明PL/SQL變量

PL/SQL變量  PL/SQL類型

Stunametable stuNameTableType;
3.訪問plsql變量/刪除plsql變量元素
 變量名(索引下標)
Declare
  Type stuNametableType is TAble of varhcar(10) Index By Binary_Integer;
  stuNametable stuNameTableType;
begin
  stunametable(2):='10';
  DBMS_Output.put_line('stunametable'||stunametable(2));
  stunametable(6):='10';
  DBMS_Output.put_line('stunametable'||stunametable(6));
  stunametable.delete(6);
  DBMS_Output.put_line('stunametable'||stunametable(6));
end;

二.記錄類型
 第一步聲明記錄類型
 1.格式
  Type 記錄類型名 is Record
  (字段1 類型| 變量%Type| 表. 字段名%Type|表%RowType [Not Null[:=表達式1],
   字段n 類型| 變量%Type|表. 字段名%Type|表%RowType[Not null[:=表達式n]);
第二步 聲明記錄類型變量
   變量 記錄類型
賦值方法
   變量名.列名
2.
  Declare
    Type stuRecordType is  Record
    ( ID Student.StuID%Type,
      Name Student.StuName%Type,
      Sex Student.Sex%Type);
  stuRec StuRecordType;  --定義記錄類型變量
  Begin
    Select StuID,StuName,Sex Into StuRec From Student
    where StuID='1001';
    DBMS_Output.put_line(stuRec.ID||''||stuRec.Name||''||stuRec.Sex);
  Exception
    when No_Data_Found then
     DBMS_OutPut.put_Line('沒有數據查詢到!);
  end;

三.嵌套表與可變數組(集合類型)

1.聲明類型 Type Table_Type is table of Type
2.定義變量及初始化 Var_Table Table_Type:=Table_type(1,3,2);
3.實例
  Declare
     type myTabletype is table of int;
     vartable mytabletype :=mytabletype(1,2,3,4.5,6,7,8,9);
  begin
    /*vartable(1):10;*/
    for i in 1..9 loop
       DBMS_Output.Put_line('ss'||vartable(i));
    end loop;
  end;
/
4.嵌套表與PL/sql表的區別

四.集合方法
 
五.批量綁定
  當集合參與數據存取時,爲提升效率而採用的方法
  Bulk collect 子句
  注 Bulk collect 能夠用於select Into 子句中
  也能夠用於遊標Fetch Bulk collect int 子句中
六,成員函數和方法
  Accessof 和multator
  注意member關鍵字的用法.

七.定義對象類型 1.定義對象類型的說明部分 Create or replace type Persontype as object (     Id Int,    Name varchar(20),    Member function GetId Return int,    Member procedure setID(pid int),    Member function GetName return  varchar,    Member procedure SetName(Pname vharchar)  ) not final; 2.實現對象的主體部分 Crate or replace type body Persontype as   member function getid return int   is   begin      Return id;   end getid;   member procedure setid(pid int) as   begin      id:=Pid;   end setid;   member function  getName return varchar as   begin      return Name;   end Getname;   member procedure setName(Pname varchar) is   begin     Name:=Pname;   end setName; end; 3.對象的使用  Declare      p persontype;  begin      p:=Persontype(1001,'tom');      DBMS_output.put_line(p.id);      DBMS_output.put_line(p.getid);      DbMS_output.put_line(p.getName);      p.setID(2001);      p.setName('Mike');  end;   4.定義對象表   Create table persontable of persontype; 5.向對象表中插入數據   Insert into persontable values(2001,'Mike');   insert into persontable values(persontype(2002,'peter')); 6.查詢對象表中的數據   select ref(o) from persontable o   select value(o) from persontable o;   select p.getid(),p.getname() from persontable p where p.id=2001  

相關文章
相關標籤/搜索