Checking if row is locked before using it in a procedure

I read your answer to How can I check whether the object xx is used/busy before using in my procedure?, and you said that you can check if anyone is locking this table by issuing a query. What would be the query to check not a table lock, but just a record, and then use my procedure SELECT FOR UPDATE NOWAIT to lock a record that I need in order to get an invoice number that cannot be repeated?

Unfortunately, there is no query which will tell you if a row is currently locked. The only query is to query V$LOCK for a transaction lock, type TX. The ID1 and ID2 columns don't point directly to the row which the transaction is locked. Rather, they point to the location in the rollback segments where the read rollback images are kept. If another transaction attempts to lock the same row, it will find the read consistent image in the rollback segments. Oracle will then know which transactions are locking on the same images in the rollback segments.

But a better way would be to do your SELECT FOR UPDATE NOWAIT and then trap for an exception. If an exception is raised, then handle it in the EXCEPTIONS area of your PL/SQL block. If it is not raised, then continue with your processing.

For More Information

Dig Deeper on Oracle database administration