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

时间:2013-07-27 11:50:03

标签: sql oracle plsql

在我的查询中,我正在使用for循环,它显示1000次三次。我必须为循环的每次迭代增加1000,即1001,1002,..相同的数字三次,即我想要添加到我的表1000,1000,1000,1001,1001,1001和1002,1002,1002,< / p>

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

我该怎么做?

1 个答案:

答案 0 :(得分:3)

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;