views:

47

answers:

2

Is there any way to select a record and update it in a single query? I tried this:

UPDATE arrc_Voucher 
  SET ActivatedDT = now() 
WHERE (SELECT VoucherNbr, VoucherID
         FROM arrc_Voucher
        WHERE ActivatedDT IS NULL
          AND BalanceInit IS NULL
          AND TypeFlag = 'V'
        LIMIT 1 )

which I hoped would run the select query and grab the first record that matches the where clause, the update the ActivatedDT field in that record, but I got the following error:

1241 - Operand should contain 1 column(s)

Any ideas?

+3  A: 

How about:

UPDATE arrc_Voucher 
  SET ActivatedDT = NOW() 
WHERE ActivatedDT IS NULL
  AND BalanceInit IS NULL
  AND TypeFlag = 'V'
LIMIT 1;
p.campbell
+1: You beat me by over a minute :( Documentation link: http://dev.mysql.com/doc/refman/5.0/en/update.html
OMG Ponies
@omg: thanks for your informative comment; I've deleted my inferior answer.
Adam Bernier
Thanks all... unsure why OP had the subquery.
p.campbell
Thanks! That did it.
EmmyS
So one more question - is there any way to get the VoucherNbr field back from the record that was selected and updated?
EmmyS
@EmmyS: Not that I'm aware of, without performing the selection prior to the update.
OMG Ponies
@EmmyS, no. See my answer
Yanick Rochon
@Adam Bernier: "inferior" is a tad strong, don't be so hard on yourself.
OMG Ponies
A: 

From the MySQL API documentation :

UPDATE returns the number of rows that were actually changed

You cannot select a row and update it at the same time, you will need to perform two queries to achieve it; fetch your record, then update it.

If you are worrying about concurrent processes accessing the same row through some kind of race condition (supposing your use case involve high traffic), you may consider other alternatives such as locking the table (note that other processes will need to recover--retry--if the table is locked while accessing it)

Or if you can create stored procedure, you may want to read this article or the MySQL API documentation.

But about 99% of the time, this is not necessary and the two queries will execute without any problem.

Yanick Rochon
I'm not sure why I need two queries; I just used OMG Ponies' answer above and it worked just fine.
EmmyS
@EmmyS, yes, this update your row from your condition. However, unless i'm misunderstanding your question, you asked to return the updated row? The answer is "you can't from an UPDATE query, unless you use a stored procedure".
Yanick Rochon
Sorry, I commented on your response before I asked about returning the updated row.
EmmyS