Programming common mistake

    In peacetime own coding and code inspection process, often there will be some error, often make repeat offenders, some production problems also lead to these errors.

1. variable used in a loop not initialized at the beginning of each cycle

Result of this is when the next cycle if there is no re-assignment to this variable, then this variable will inherit the value assigned when the last cycle, but this is often not what we want.

As an example, when a grade = 4, salary is 1000, and 0 otherwise.

 

 1  declare
 2     v_salary  number  : =   0 ;  
 3  begin
 4     for  rec  in  ( select  name,address,grade  from  people)
 5    loop
 6      
 7       if  rec.grade  =   ' 4 '
 8       then
 9        v_salary : =   1000 ;
10       end   if ;
11      
12       insert   into  salary(name,salary)  values  (rec.name,v_salary);
13      end  loop;
14  end ;
15        
16      

 

 In the beginning of each iteration the above code is not reinitialized v_salary variable start, the following values ​​v_salary grade = 4 so there are 1000 from the first time.

The correct approach is the variable used in a loop, in each cycle, should be re-initialized, unless you specifically do initialization to achieve your goal.

Reproduced in: https: //www.cnblogs.com/MichaelGuan/archive/2010/11/14/1876968.html

Guess you like

Origin blog.csdn.net/weixin_33756418/article/details/94290101