views:

130

answers:

2

I'm a little rusty with my triggers and what not and am trying to figure out this problem for a class:

In a database TEST, tables do not have the option of the IDENTITY feature. In other words, when we insert a row into the table “Users”, we would like the primary key “UserID” to auto-increment. Please suggest a workaround to implement this feature without such a built-in functionality. (Hint: You may still use functions, stored procedures, sequences, triggers, etc)

Any takers on this ?

Thanks

A: 

You use a sequence, and it's very common with Oracle, which does not (or did not once, it may have changed) have identity columns. Since this is homework I'll let you figure out the rest from here.

Joel Coehoorn
+1  A: 

Use an Int column for the table Primary Key called ID.

You can then use an instead of Insert Trigger, to populate/calculate the value to be inserted for ID.

The trigger will determine what the maximum existing ID is for the table in question (using select MAX ID from TableA) and then increment it by 1 for each record to be inserted.

If there are no records in the table then the ID value is 1.

John Sansom
It's important here to note that your transaction isolation mode here is critical! If you are using a normal READ COMMITTED isolation level, it is possible that two processes could generate the same ID, which would be a Bad Thing indeed. So you'll need to use a SERIALIZABLE isolation level inside the trigger, or you could be in trouble. Or better yet, avoid it altogether and use an IDENTITY ;-)
Dave Markle
@Dave +1: A very important point to consider.
John Sansom