2

我是 SQL 和 Oracle 的新手,所以为了练习,我创建了一个虚拟表来跟踪我的打字学习课程(因为我从来没有学过打字,所以我现在正在弥补它),并使用这个设置一个序列在 Oracle 中查询:

CREATE SEQUENCE seq_keyboard_learning
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10

我的意图是让我的 id 列增加,但每次我添加一个新值时它都会从 1 跳到 5,等等。为了完整起见,以下是我在设置此表时使用的一些查询。

CREATE TABLE keyboard_learning
(
emplid NUMBER CONSTRAINT emplid_pk PRIMARY KEY
,WPM NUMBER
,date_completed DATE
)

CREATE SEQUENCE seq_keyboard_learning
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10

INSERT INTO keyboard_learning (emplid,wpm,date_completed)
VALUES (seq_keyboard_learning.nextval,15,'12-JUN-2012')

UPDATE keyboard_learning 
SET emplid = 1
WHERE emplid = 4

ALTER TABLE keyboard_learning
ADD attempt VARCHAR2(45)

INSERT INTO keyboard_learning
VALUES (seq_keyboard_learning.nextval,26,'6-JUN-2012','ASDFJKL:',2)

而不是每 4 个术语增加一次,我该如何调整?谢谢

4

1 回答 1

3

确保你有一个没有间隙的序列基本上是不可能的。请记住,从序列中获取是原子操作,因此如果您插入记录并遇到错误,序列仍将递增。请参见下面的示例。

拥有缓存也可能导致您“丢失”序列。如果我在缓存中指定值 10,数据库将从序列中缓存 10。如果只插入 2 行并关闭数据库,则丢弃其他 8 行。注意:由 Alex Poole 编辑并更正。

我希望这有助于理解序列的一些行为。

create table test
(id     number,
my_date date);

select seq.currval from dual;

insert into test
(id, my_date)
values (seq.nextval, 'foo'); -- will throw an exception

select seq.currval from dual;

结果是:

table TEST created. 
CURRVAL
-------
      1 


Error starting at line 31 in command: insert into test (id, my_date) values (seq.nextval, 'foo') Error report: SQL Error: ORA-01858: a non-numeric character was found where a numeric was expected
01858. 00000 -  "a non-numeric character was found where a numeric was expected"
*Cause:    The input data to be converted using a date format model was
           incorrect.  The input data did not contain a number where a number was
           required by the format model.
*Action:   Fix the input data or the date format model to make sure the
           elements match in number and type.  Then retry the operation. 
CURRVAL
-------
      2
于 2012-06-14T01:29:13.240 回答