views:

57

answers:

3

I have the following table with the value 501 in it..

CREATE TABLE _Numbers(
    Number numeric(20,0) NOT NULL PRIMARY KEY
)
INSERT INTO _Numbers VALUES(501)

How can I write a stored proc on this which returns me 501 and increments Number to next in sequence (i.e. 502)? I would like this behaviour repeated every time the stored proc is called.

(Also, how can I call this stored proc from any query?)

Part of my previous question 3151056.

Thanks,

Voodoo

+1  A: 
CREATE OR REPLACE PROCEDURE read_and_increment (number_just_read OUT NUMBER)
IS
BEGIN
   DECLARE
      stored_number   NUMBER DEFAULT NULL;
   BEGIN
      SELECT number
        INTO stored_number
        FROM _numbers
       WHERE ROWNUM = 1;

      number_just_read := stored_number;

      UPDATE _numbers
         SET number = number + 1;

      COMMIT;
   END;
END read_and_increment;
The chicken in the kitchen
I have supposed that the _NUMBERS table contain only one significative record, and that we HAVEN'T concurrency problems (i.e. simultaneous reads, and so on).
The chicken in the kitchen
@Chicken :) -> not with this table we wont have concurrency problems. But what would happen if there are simultaneous reads? Would the db session not be locked by thread one and the other thread is just waiting around for it? (sry if this is kind of a noob question)
VoodooChild
In one microsecond, two users can read (and produce in the output) the same value, incrementing the NUMBER field two times.
The chicken in the kitchen
+3  A: 

Use an IDENTITY column which takes care of numbering and incrementing for you.

Any returned number is liable to be already used by another connection/client/process

gbn
@gbn: I don't think I could use IDENTITY in my case because I am moving data over from quiet a few a old tables some of which have this number to be used set and some of them are NULL. please see my previous question posted to learn what I wanted to do http://stackoverflow.com/questions/3151056/sql-stored-proc-help-me-write-this-one-please - Thanks for your answer
VoodooChild
+2  A: 

You're importing data from old tables, right? What if you import data from old tables with identity off and after that you set the identity with the highest number+1 and continue your life using identity.

Other approach is using a trigger at insert that would check if NumberItem is null and it will add the Max+1 if it's null. If not, do nothing.

I don't think that SP is a good solution. And I'm pretty sure you don't need all that stuff.

Bruno Costa