2013-03-19 126 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