oracle sequence 妙用

在生产环境中,常有一些生产流水表是用生产流水的id号作为主键,如何让主键进行自我递增呢?

可以结合sequence和procedure来达到这个目的:

首先建立一张流水表如下:

SQL> desc cost_log
Name       Type         Nullable Default Comments
---------- ------------ -------- ------- --------
CID        NUMBER                                
USERID     NUMBER                                
DATETIME   DATE         Y                        
RUNNO      VARCHAR2(10) Y                        
CARDNO     VARCHAR2(10)                          
MONEY      NUMBER       Y                        
SERVERNAME VARCHAR2(10) Y

在建立一个sequence:

CREATE SEQUENCE  "SCOTT"."COST_SEQ"  MINVALUE 1 MAXVALUE 10000 INCREMENT BY 1 START WITH 2 CACHE 20 NOORDER  CYCLE ;

在建立procedure:

SQL> create or replace procedure add_cost_log(
  2  p_userid in number,
  3  p_runno in varchar2,
  4  p_cardno in varchar2,
  5  p_money in number,
  6  p_servername in varchar2)
  7  as
  8  begin
  9  insert into cost_log(
 10  cid,
 11  userid,
 12  runno,
 13  cardno,
 14  money,
 15  servername)
 16  values
 17  (cost_seq.nextval,
 18  p_userid,
 19  p_runno,
 20  p_cardno,
 21  p_money,
 22  p_servername);
 23  commit;
 24  end add_cost_log;
 25  /
 
Procedure created

最后调用存储过程,进行测试。

SQL> declare
  2  i_userid cost_log.userid%type :=101;
  3  i_runno cost_log.runno%type :='101';
  4  i_cardno cost_log.cardno%type :='101';
  5  i_money cost_log.money%type :=101;
  6  i_name cost_log.servername%type :='hello';
  7  begin
  8    add_cost_log(i_userid,i_runno,i_cardno,i_money,i_name);
  9  end;
 10  /
 
PL/SQL procedure successfully completed

SQL> /
 
PL/SQL procedure successfully completed
 
SQL> /
 
PL/SQL procedure successfully completed

SQL> select * from cost_log;
 
       CID     USERID DATETIME    RUNNO      CARDNO          MONEY SERVERNAME
---------- ---------- ----------- ---------- ---------- ---------- ----------
         2        101             101        101               101 hello
         3        101             101        101               101 hello
         4        101             101        101               101 hello

如此,就可以简单的使用了。

本文出自 “广袤苍穹” 博客,谢绝转载!

你可能感兴趣的:(oracle,职场,sequence,procedure,休闲)