in reply to checking to do a insert or update

If you can identify a "primary key" value in the data that you're putting into the table -- e.g. if the combination of "round" and "playername" should never repeat in the table -- then you could start with a query that pulls out all the existing "round,playername" tuples in the table, and store those as keys to a hash (values assigned to those keys won't matter, just so long as the keys are made to exist).

Then, use the "prepare" method in DBI to create two SQL statement handles -- one for update, and one for insert.

Now, as you go through the "weekly_file", check each "round,playername" value to see if it exists as a hash key from that initial query -- if it's there, use the update statement handle, otherwise, use the insert.

I wrote a wrapper for DBI that makes this sort of thing fairly simple to code in Perl (the pod even gives an example a bit like this) -- I'm not claiming it's the "best" or "optimal" solution, but it works for me, and saves me a lot of time when writing Perl code for SQL operations like this.

Replies are listed 'Best First'.
Re: Re: checking to do a inser or update
by dsheroh (Monsignor) on Jun 07, 2002 at 15:44 UTC
    Another similar variation, which I typically use, is to check whether the record exists (either using a hash, as described, or by doing a SELECT if there's a reasonable possibility of the database having been changed), then call a stock INSERT to create a dummy record if it's not already there, and finally run a standard UPDATE regardless of the initial search's result.

    Less efficient in execution, but easier to work with since I only need to keep a single UPDATE statement current rather than both an INSERT and an UPDATE.