in reply to Increase a value inside MySQL query using perl

kcott raised the most important points. To expand on that a bit...

The first time you execute an SQL statement like this:

update table set ID = 10 where ID = 5"
that one execution will cause every row with ID=5 to updated to ID=10. If you execute the exact same statement a second time (e.g. trying to set ID=11 instead of 10), nothing will happen, because you no longer have any rows with ID=5 (all those rows now have ID=10).

I would suggest using a SELECT statement to get all the rows having ID=5, and then for each row returned by that query, do an update with desired new value for ID:

my $update_sth = $dbh->prepare( "update table set ID=? where ID=5 and +Name=?"); my $select_sth = $dbh->prepare( "select Name from table where ID=5" ); my $new_ID = 10; $select->execute; while ( my $row = $select->fetchrow_arrayref ) { my $name = $$row[0]; $update_sth->execute( $new_ID++, $name ); }
(You should probably add some error checking, to make sure the updates work as intended.)

Updated to fix a typo in the 2nd line of the code snippet (was "IS=5") -- thanks kcott!

Replies are listed 'Best First'.
Re^2: Increase a value inside MySQL query using perl
by Anonymous Monk on Oct 14, 2015 at 03:01 UTC

    graff: kcott raised the most important points. To expand on that a bit...

    Kind sorta almost ... the question/problem feels more at the fizz-buzz stage, the OP has a good idea (almost) its just translating it into code, and working through the hurdles, thats the issue

    For example, if he can get $max to affect add_max ... then notice the issue with the update you mentioned

    then its just a matter of adding a update limit clause