规则序列化

202 阅读1分钟

Oracle中,当需要建立一个自增字段时,需要用到sequence。在oracle中sequence就是序号,每次取的时候它会自动增加,与表没有关系。

创建sequence

CREATE SEQUENCE #{sequence title}
INCREMENT BY 1 -- 每次加几个
START WITH 1 -- 从1开始计数
MINVALUE 1 -- 序列最小值
NOMAXVALUE/MAXVALUE -- 不设置最大值/序列最大值
NOCYCLE -- 一直累加,不循环
CACHE 10; --设置缓存cache个序列,如果系统down掉了或者其它情况将会导致序列不连续,也可以设置为---------NOCACHE

获取指定序列号的值

-- 获取下一个序列号
select #{sequence title}.nextval from dual;
or
select last_number from user_sequences where sequence_name='#{sequence title}'
-- 获取当前序列号
select #{sequence title}.currval from dual;

查询已创建的序离号

-- 查询当前用户下已创建的序离号
select sequence_name from user_sequences
-- 查询所有用户下创建的序列号
SELECT sequence_owner 用户名,sequence_name 序列号名称 FROM all_sequences

导出指定的序列号

oracle 的exp命令没有导出sequence的选项,可使用以下查询语句将要导出的sequence拼接成创建语句

-- 查询指定用户
select 'create sequence ' || sequence_name || ' minvalue ' || min_value ||
       ' maxvalue ' || max_value || ' start with ' || last_number ||
       ' increment by ' || increment_by || (case
         when cache_size = 0 then
          ' nocache'
         else
          ' cache ' || cache_size
       end) || ';'
  FROM user_sequences
 where sequence_name in (#{指定的sequence})
-- 查询所有用户
select 'create sequence ' || sequence_name || ' minvalue ' || min_value ||
       ' maxvalue ' || max_value || ' start with ' || last_number ||
       ' increment by ' || increment_by || (case
         when cache_size = 0 then
          ' nocache'
         else
          ' cache ' || cache_size
       end) || ';'
  FROM all_sequences
 where sequence_owner = 'WDPHIS'
   and sequence_name in (#{指定的sequence})