-1

i just created a java file to parse a csv files and saved them into an oracle database.. but i need a field ID which acts as a primary key.. and i am a bit confused abt looping..

Praneel PIDIKITI
  • 18,677
  • 13
  • 41
  • 60
  • Please come back when you are less confused over what your problem is. I suspect that a Google for "Oracle Sequence" would give you some hints. – Ronnis Feb 14 '11 at 09:23
  • I'm a bit confused about your question... – tbone Feb 14 '11 at 12:47
  • i have a csv file which is transfered into a oracle database.. now the pbm is i need a serial number field for the table i created .. can i implement the logic in the java program i am writing? – Praneel PIDIKITI Feb 14 '11 at 14:07

1 Answers1

1

I think all you need to do is utilize a sequence (as suggested by Ronnis)

as such

CREATE SEQUENCE FIELD_ID_SEQ START WITH 1 INCREMENT BY 1 NOCYCLE NOCACHE; 
/*NOTE THE SEQUENCE, WHILE INCREMENTING, IS NOT GUARANTEED TO BE 1,2,3,4...N ->expect gaps in the #*/

Now either in your java app where you are saving the data:

"INSERT INTO TABLE_OF_CSV(FIELD_ID, FIELD_COLA, FIELD_COLB) VALUES(FIELD_ID_SEQ.NEXTVAL, ?,?);"

OR


Now if you are using a procedure (or a procedure within a package) you can do this (note this returns the primary key back to the calling app)

create procedure insertIntoCSVTable(pCOLA IN TABLE_OF_CSV.FIELD_COLA%TYPE 
                                  , pCOLB IN TABLE_OF_CSV.FIELD_COLB%TYPE
                                  , pFIELD_ID OUT TABLE_OF_CSV.FIELD_ID%TYPE)
AS
BEGIN

    INSERT INTO TABLE_OF_CSV(FIELD_ID, FIELD_COLA, FIELD_COLB) 
    VALUES(FIELD_ID_SEQ.NEXTVAL, pCOLA, pCOLB)
    RETURNING FIELD_ID
    INTO pFIELD_ID
    ;

END insertIntoCSVTable;

no looping required assuming you are already looping in your java code (assuming a row-by-row insert)


OR


You may use a trigger to insert a new value into the table: create or replace

TRIGGER TABLE_OF_CSV_TRG BEFORE INSERT ON TABLE_OF_CSV 
FOR EACH ROW 
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF :NEW.FIELD_ID IS NULL THEN
      SELECT FIELD_ID_SEQ.NEXTVAL INTO :NEW.FIELD_ID FROM DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;

Harrison
  • 8,970
  • 1
  • 32
  • 28