Manaully generating your own Id int value

If you ever find yourself adding a row to a table that has a primary key int field that is not set as an Identity column, meaning it won’t create an Id for itself on inserts, then you need to insert your own Id value.

Of course the database should be responsible for this and the database should be fixed, but assuming you don’t have the authority to fix the database, and you are stuck working with a poorly designed table and you must insert a row, and to insert that row you must generate your own int Id value that is 1 greater than the Max Id, here is what the insert will look like:

Insert into MyBadlyDesignedTable (Id, Name ,ExpirationDate, Position)
values
(
  (select  MAX(Id) + 1  from MyBadlyDesignedTable)
  , 'Bob' 
  ,'1/15/2015'
  ,1
)

Or if you want to return the new ID you can do this:

Declare @newId int
select @newId = MAX(Id) +1  from MyBadlyDesignedTable

Insert into MyBadlyDesignedTable (Id, Name ,ExpirationDate, Position)
values
(
  @newId
  , 'Bob' 
  ,'1/15/2015'
  ,1
)

Select @newId

If you can fix your database, then do it. But if you can’t because it is a legacy system, then this will work*.

* I do worry that the a race condition may cause this fail if 2 inserts try to use the same key because they run their ‘select Max’ at the exact same time. If you know a better/safer way to do this, please leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s