我有一个表人包含的字段是personName,personId并且没有指定主要我在表中添加了一些值。表Person中的值为
('muni',1)
('Ganesh',1)
我需要将主键添加为personId,并将列修改为autogenerated。所以,我尝试通过以下查询生成序列,以生成触发器
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
,表示我给出的号码无效号码。但我不知道错误在哪里?
任何帮助高度赞赏。
答案 0 :(得分:1)
试试这个
select nvl(max(rownum),0)+1 into id from Person;
当表为空时,max(rownum)将返回null,当您向值添加null时将始终返回null,因此您需要将任何空值转换为0,以便0 + 1将返回1而不是null
答案 1 :(得分:1)
upd:刚注意到比计数/ 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
答案 2 :(得分:0)
像这样创建一个序列
CREATE SEQUENCE person_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
比使用 - ' person_seq.nextval'每次插入新记录
e.g。
插入人(姓名,身份证)值(' abc',person_seq.nextval)