0

我有一个表 Person 包含字段是 personName,personId 并且没有指定主要我在表中添加了一些值。表 Person 中的值是

 ('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;

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

4

3 回答 3

1

尝试这个

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

当表为空时 max(rownum) 将返回 null 并且当您将 null 添加到值时将始终返回 null,因此您需要将任何 null 转换为 0 以便 0 + 1 将返回 1 而不是 null

于 2013-03-19T04:07:19.420 回答
1

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

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

您可以通过以下方式检查值是否为空:id is null.

空值

使用count(*).

12:03:55 SYSTEM@saz-dev> 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 SYSTEM@saz-dev> 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 SYSTEM@saz-dev> select object_name from user_objects where object_name = 'PERSONSEQ';

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

Elapsed: 00:00:00.08
12:06:16 SYSTEM@saz-dev> truncate table person;

Table truncated.

Elapsed: 00:00:00.32
12:06:27 SYSTEM@saz-dev> drop sequence personseq;

Sequence dropped.

Elapsed: 00:00:00.20
12:06:33 SYSTEM@saz-dev>  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 SYSTEM@saz-dev> select personseq.nextval from dual;

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

Elapsed: 00:00:00.04
于 2013-03-19T04:07:39.547 回答
0

像这样创建一个序列

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

而不是使用 - 'person_seq.nextval' 用于每次插入新记录,
例如

插入人(姓名,身份证)值('abc',person_seq.nextval)

于 2013-03-19T04:07:08.220 回答