Monday, March 26, 2012

How to insert a new unique INT if none is given

I've got a table name Messages and each message has a MessageID (the primary, auto-generated column) and a ThreadID (for grouping replies together). When I create a new message, I want to insert a new ThreadID if none is given to the stored procedure. I'm looking for something like NewID() as the default value but that inserts a NewInt. Do I have to write my own trigger?

And I know ThreadID should be a foreign key to a Threads table but I'm keeping it simple for now. I have the option of making that later if I like.

Thanks.

In Oracle, you would set up a sequence and ask it for the next number. Piece of cake!

I can think of two ways to do it in Sql Server.

The first is the easiest and, to my mind, the best. Create a Threads table with a ThreadId column that is an identity column. Create a trigger on your Messages table. It's simple, it's clean, and it's the right thing to do. :)

The second is to write a trigger that queries the messages table and returns the highest threadid value you find (+ 1). The problem is that, in a multi-user environment, you will have to lock the entire Messages table first to prevent anyone else from running that query until your insert finishes. Otherwise, you will get two different, unrelated messages with the same thread id. It's nasty, prone to error, and actually harder than doing the right thing.

No comments:

Post a Comment