Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle pl/sql script which increments number

Tags:

oracle

plsql

Looking for a way to create an Oracle script using the equivalent of java ++ syntax to increment a variable.

Ie:

int id=10
DELETE MYTABLE;
INSERT INTO MYTABLE(ID, VALUE) VALUES (id++, 'a value');
INSERT INTO MYTABLE(ID, VALUE) VALUES (id++, 'another value');
...

Trying to use a variable and not a sequence so I can rerun this multiple times with the same results.

like image 215
Marcus Leon Avatar asked May 22 '15 19:05

Marcus Leon


2 Answers

PL/SQL doesn't have the ++ syntactic sugar. You'd need to explicitly change the value of the variable.

DECLARE
  id integer := 10;
BEGIN
  DELETE FROM myTable;
  INSERT INTO myTable( id, value ) VALUES( id, 'a value' );
  id := id + 1;
  INSERT INTO myTable( id, value ) VALUES( id, 'another value' );
  id := id + 1;
  ...
END;

At that point, and since you want to ensure consistency, you may be better off hard-coding the id values just like you are hard-coding the value values, i.e.

BEGIN
  DELETE FROM myTable;
  INSERT INTO myTable( id, value ) VALUES( 10, 'a value' );
  INSERT INTO myTable( id, value ) VALUES( 11, 'another value' );
  ...
END;
like image 65
Justin Cave Avatar answered Nov 08 '22 21:11

Justin Cave


You can create a SEQUENCE to increment a number.

----CREATING SEQUENCE:                                                                                                                                                      

    SQL> create sequence seq_name
    2  start with 1
    3  increment by 1
    4  NOCACHE
    5  NOCYCLE
    6  ;

Sequence created.

----EXECUTION:                                                                                                                                            
SQL> select seq_name.nextval from dual;   

NEXTVAL                                                                                                                                         
1

SQL> select seq_name.nextval from dual;                                                                                                                 

NEXTVAL     
2    

Also you can create a function that can be called anywhere:

----CREATING FUNCTION:     
create or replace function sequence_func(a_number IN Number)
RETURN Number
AS
id Number;                                                                                                                                         
Begin                                                                                                                                              
select seq_name.nextval into id from dual;    
Return id;
end;
/

Function created.

----EXECUTION:  
SQL> select  sequence_func(1) seq from dual;  
seq
1  

P.S : startwith and increment by values below can be set as per your requirement.

like image 36
mahi_0707 Avatar answered Nov 08 '22 22:11

mahi_0707