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?

Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
EmmyS
  • 11,892
  • 48
  • 101
  • 156

2 Answers2

3

How about:

UPDATE arrc_Voucher 
  SET ActivatedDT = NOW() 
WHERE ActivatedDT IS NULL
  AND BalanceInit IS NULL
  AND TypeFlag = 'V'
LIMIT 1;
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
p.campbell
  • 98,673
  • 67
  • 256
  • 322
0

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
  • 51,409
  • 25
  • 133
  • 214
  • I'm not sure why I need two queries; I just used OMG Ponies' answer above and it worked just fine. – EmmyS Oct 28 '10 at 19:27
  • @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 Oct 28 '10 at 19:30
  • Sorry, I commented on your response before I asked about returning the updated row. – EmmyS Oct 28 '10 at 23:03
  • 1
    99% means one out of every 100 queries will fail. ;) – devios1 Mar 16 '12 at 18:28