博客分类: DB-oracle sqlOracle 1、方式一:使用序列和触发器 Sql代码 收藏代码 SQL> CREATE SEQUENCE te

1、方式一:使用序列和触发器 

Sql代码   收藏代码
  1. SQL> CREATE SEQUENCE test_sequence2  
  2.   2    increment by 1    -- 每次递增1  
  3.   3    start with 1       -- 从1开始  
  4.   4    nomaxvalue      -- 没有最大值  
  5.   5    minvalue 1       -- 最小值=1  
  6.   6    NOCYCLE;      -- 不循环  
  7.   
  8. Sequence created.  
  9.   
  10. SQL> CREATE TABLE test_create_tab2 (  
  11.   2    id   INT,  
  12.   3    val  VARCHAR(10),  
  13.   4    PRIMARY KEY (id)  
  14.   5  );  
  15.   
  16. Table created.  
  17.   
  18. SQL> CREATE OR REPLACE TRIGGER BeforeTestCreate2Insert  
  19.   2    BEFORE INSERT ON test_create_tab2  
  20.   3  FOR EACH ROW  
  21.   4  BEGIN  
  22.   5    SELECT test_sequence2.nextval INTO :new.id  FROM dual;  
  23.   6  END;  
  24.   7  /  
  25.   
  26. Trigger created.  
  27.   
  28. SQL> INSERT INTO test_create_tab2(val) VALUES ('NO id');  
  29.   
  30. 1 row created.  
  31.   
  32. SQL> INSERT INTO test_create_tab2(id, val) VALUES (1, 'id no use');  
  33.   
  34. 1 row created.  
  35.   
  36. SQL> SELECT * FROM test_create_tab2;  
  37.   
  38.         ID VAL  
  39. ---------- --------------------  
  40.          1 NO id  
  41.          2 id no use  

2、方式二:仅使用序列 
Sql代码   收藏代码
  1. [TEST1@orcl#27-12月-10] SQL>create table y_one(id number);  
  2.   
  3. 表已创建。  
  4.   
  5. [TEST1@orcl#27-12月-10] SQL>create sequence y_seq start with 1 increment by 1 nomaxvalue nocycle  
  6.   2  ;  
  7.   
  8. 序列已创建。  
  9.   
  10. [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);  
  11.   
  12. 已创建 1 行。  
  13.   
  14. [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);  
  15.   
  16. 已创建 1 行。  
  17.   
  18. [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);  
  19.   
  20. 已创建 1 行。  
  21.   
  22. [TEST1@orcl#27-12月-10] SQL>commit;  
  23.   
  24. 提交完成。  
  25.   
  26. [TEST1@orcl#27-12月-10] SQL>select * from y_one;  
  27.   
  28.         ID  
  29. ----------  
  30.          1  
  31.          2  
  32.          3  

1、创建表

create table note(  
id number(20) NOT NULL primary key,/*主键,自动增加*/                 name varchar2(20)); 

2、创建自动增长序列

 Create Sequence addAuto_Sequence 
 Increment by 1     -- 每次加几个 
 start with 1       -- 从1开始计数     
 nomaxvalue         -- 不设置最大值,设置最大值:maxvalue 9999  
 nocycle            -- 一直累加,不循环    
 cache 10;  

3、创建触发器

 Create trigger addAuto before 
 insert on note(表名) for each row /*对每一行都检测是否触发*/
 begin
 select addAuto_Sequence.nextval into:New.id from dual;
 end;      
4、提交 commit;

5、测试 insert into note(name) values(‘lisi’);

 

猜你喜欢

转载自m635674608.iteye.com/blog/2386395