繁体   English   中英

使用PL / SQL增加表中的值?

[英]Incrementing values in table using PL/SQL?

在我的查询中,我使用了for循环,该循环显示1000次3次。 我必须为循环的每次迭代增加1000,即1001、1002,..相同的次数三次,即我想将1000、1000、1000、1001、1001、1001和1002、1002、1002添加到表中

declare
   CPName varchar(20) :=1000;
   a number; 
begin
   for a in 1 .. 3 loop
       insert into clients values (CPName,null,null);
   end loop;    
end;

我怎样才能做到这一点?

CPName是一个VARCHAR; 我假设您希望它是一个数字,在这种情况下,您只需添加它即可。

也不需要定义变量a ,它由LOOP隐式声明。 我将其称为i因为它是索引变量的更常用名称。

declare
   CPName integer := 1000;
begin
   for i in 1 .. 3 loop
       insert into clients values (CPName + i, null, null);
   end loop;    
end;

不过,您可以在单个SQL语句中完成所有操作; 无需使用PL / SQL。

insert into clients
 select 1000 + i, null, null
   from dual
  cross join ( select level as i
                 from dual
              connect by level <= 3 )

根据您的评论,您实际上想要这样的东西:

insert into clients
with multiply as (
 select level - 1 as i
   from dual
connect by level <= 3
        )
 select 1000 + m.i, null, null
   from dual
  cross join multiply m
  cross join multiply

仅当您希望增加记录数量时才可以使用此功能,因此也许您希望以这种方式进行操作,这将为您带来更大的灵活性:

insert into clients
with increments as (
 select level - 1 as i
   from dual
connect by level <= 5
        )
, iterations as (
 select level as j
   from dual
connect by level <= 3
        )
 select 1000 + m.i, null, null
   from dual
  cross join increments m
  cross join iterations

使用您的LOOP方法,这将涉及第二个内部循环:

declare
   CPName integer := 1000;
begin
   for i in 1 .. 3 loop
      for j in 1 .. 3 loop
         insert into clients values (CPName + i, null, null);
      end loop;
   end loop;    
end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM