Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a database table that has 2 columns, an ID and name. Lets say there are already 5 records in this table all with appropriate ID numbers (1-5). When inserting new records, how can I properly add them with the correct (the following) ID numbers?

Replies are listed 'Best First'.
Re: inserting new data into table
by coreolyn (Parson) on Jan 03, 2001 at 00:57 UTC

    Your question is a bit vauge in that the answer you are looking for is dependant on how you are accessing the database (Perl DBI?) and what type of database you are accessing.

    If your ID tag in your DB is set to autonumber you don't have to sweat incrementing the ID. If your using a flat-file db or berkley you'll need to specify that in your question, and I'm sure someone would have the most correct answer.

    coreolyn

Re: inserting new data into table
by tune (Curate) on Jan 03, 2001 at 01:17 UTC
    in mysql and postgres you can use auto_increment columns, and in Oracle a sequence will help you

    -- tune

Re: inserting new data into table
by tame1 (Pilgrim) on Jan 03, 2001 at 02:35 UTC
    Perhaps, as the others have said, you can choose "auto_increment" as the column type
    to cause this behavior automatically. (For example, your SQL to insert a new entry would read something like "insert into TABLE values(NULL, myname)" and the db engine would increment the value in the first column.

    Also, you could use "select MAX(ID) from TABLE", add one to this value, and manually increment like that.

    What does this little button do . .<Click>; "USER HAS SIGNED OFF FOR THE DAY"

      Also, you could use "select MAX(ID) from TABLE", add one to this value, and manually increment like that.

      Of course, you'll only do this with a table lock won't you? (assuming you don't have transactions (MySQL etc), or have AUTO_COMMIT on).

      Otherwise imagine two INSERTs happening simultaneously ... someone else could quite happily come along and INSERT something else in between *your* SELECT and INSERT... leaving you with quite a nasty race condition.

      Tony

        Oh yeah - What Tony said ;-)

        What does this little button do . .<Click>; "USER HAS SIGNED OFF FOR THE DAY"