2013-03-19 123 views
0

我有一个表Person包含字段是personName,personId,没有指定主要我在表中添加了一些值。 Person表中的值为Oracle序列没有生成

('muni',1) 
('Ganesh',1) 

我需要将主键添加为personId并将该列修改为自动生成。所以,我试图生成由以下查询序列生成触发作为

declare   
id number;  
begin 
select max(rownum)+1 into id from Person; 
execute immediate 'create sequence personseq start with '||to_char(id); 
end; 

如果当值表中的我执行上面的查询,然后将它正确地执行,但是当我有空表表示表中没有条目,则上述查询不会生成序列。

我也试过if语句。

declare 
id number; 
begin 
select max(rownum)+1 into id from Person; 
if (id=null) then 
execute immediate 'create sequence personseq start with '||to_char(1); 
else 
execute immediate 'create sequence personseq start with '||to_char(id); 
end if; 
end; 

系统说错误号是ORA01722,它表示我给的号码无效号码。但我不知道错误在哪里?
任何帮助高度赞赏。

回答

1

试试这个

select nvl(max(rownum),0)+1 into id from Person; 

当表是空的MAX(ROWNUM)将返回null,当你添加null值将始终返回null,因此您需要将任何空值转换为0,以便0 + 1将返回1而不为空

+0

我已经在我的学校日阅读过这个概念,但我真的忘记了nvl。感谢提醒。 – MGPJ 2013-03-19 04:11:38

+0

你能告诉我为什么If语句不工作 – MGPJ 2013-03-19 04:19:29

+0

@muniganesh,检查更新的答案 – 2013-03-19 05:11:10

0

创建序列一旦像这样

CREATE SEQUENCE person_seq 
START WITH  1000 
INCREMENT BY 1 
NOCACHE 
NOCYCLE; 

比使用 - “person_seq.nextval”的新的记录的
例如每个插入

插入到人(姓名,身份证)VALUES( 'ABC',person_seq.nextval)

+0

我同意,这比从表格中选择最大值更可靠和更高效 – 2013-03-19 06:19:35

1

upd:刚注意到比count/rownum更重要的缺陷。

id=null。永远不要这样做,这是行不通的。

您检查一个值是否为空:id is null

NULLS

使用count(*)

12:03:55 [email protected]> create table person as 
12:04:05 2 select 'muni' name, 1 attribute from dual union all 
12:04:32 3 select 'ganesh' name, 1 attribute from dual; 

Table created. 

Elapsed: 00:00:00.07 
12:04:47 [email protected]> ed 
Wrote file S:\tools\buffer.sql 

    1 declare 
    2 id number; 
    3 begin 
    4 select count(*)+1 into id from person; 
    5 execute immediate 'create sequence personseq start with '||to_char(id)||' increment by 1'; 
    6* end; 
12:05:52 7/

PL/SQL procedure successfully completed. 

Elapsed: 00:00:00.06 
12:05:53 [email protected]> select object_name from user_objects where object_name = 'PERSONSEQ'; 

OBJECT_NAME 
--------------------------------------- 
PERSONSEQ 

Elapsed: 00:00:00.08 
12:06:16 [email protected]> truncate table person; 

Table truncated. 

Elapsed: 00:00:00.32 
12:06:27 [email protected]> drop sequence personseq; 

Sequence dropped. 

Elapsed: 00:00:00.20 
12:06:33 [email protected]> declare 
12:06:38 2 id number; 
12:06:38 3 begin 
12:06:38 4 select count(*)+1 into id from person; 
12:06:38 5 execute immediate 'create sequence personseq start with '||to_char(id)||' increment by 1'; 
12:06:38 6 end; 
12:06:39 7/

PL/SQL procedure successfully completed. 

Elapsed: 00:00:00.03 
12:06:40 [email protected]> select personseq.nextval from dual; 

    NEXTVAL 
---------- 
     1 

Elapsed: 00:00:00.04