简体   繁体   中英

How to update exactly one record and select updated row in a single db2 query

I want to write a query which updates only one row of a table then returns updated rows.

I can achieve getting returned rows using

select field from final table 
(update tablename set anotherfield = 'dd' where someanotherfield = 'bb')

kind of statement. But i cannot update just one row.

Also my program that calls this query is a multithreaded one and i dont want to deadlock any processes so, i found SKIP LOCKED DATA statement which is like readpast in t-sql query.

So what i am trying to do is, my program uses an db2 table like a stack, selects only one row each time, updates it so any other thread cannot access it but does not make them wait entire table, they just skip updated row and select next record from table. Is this operation possible in a single db2 query?

I have written this query so far, and it cannot be processed

select COLUMN3 FROM FINAL TABLE
   ( 
      update MYTABLE 
      set    COLUMN1 = 'R'
      where  COLUMN1 = ''
          order by COLUMN2 
          FETCH FIRST 1 ROW ONLY 
          SKIP LOCKED DATA 
   )

Any help would be appreciated, Thanks.

Assuming that COLUMN2 is a unique_id , you could do something like this:

select COLUMN3 FROM FINAL TABLE
( 
    update MYTABLE 
    set    COLUMN1 = 'R'
    where  COLUMN1 = ''
        AND COLUMN2 = ( SELECT COLUMN2 
                        FROM MYTABLE 
                        ORDER by COLUMN2 
                        FETCH FIRST 1 ROW ONLY)
    SKIP LOCKED DATA 

)

You were doing an order by inside your update and that doesn't work. You have to restrain that to only one result (likely using your primary key).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM