Home » Programming / Coding

Insert Max int Type Primary Column Value + 1 – Microsoft Sql

2 March 2011 1,806 views No Comment

If you have a primary column of type int, you need to insert unique values for it, best approach is set the column IS IDENTITY type true with identity seed 1. That way you wont have to worry about it.

However in some cases you might not be able to do that. Recently i had to work for a large health provider in MA area. They gave me an access to the db without proper privileges, which doesn’t allow me set the column IS IDENTITY true. Since i am in rush to finish i have to come up with a way i could insert unique incremental values for the int primary key column on a table.

insert into MyTable(tId)
Select IsNull((Select Max(IsNull(tId,0))+1 from MyTable),1)

Note that I have to wrap the inner subquery in a IsNull for the case when there is no rows in table.
_______________________
From Webcosmo Webmaster Forum http://www.webcosmoforums.com/databases/27236-insert-max-int-type-primary-column-value-1-microsoft-sql.html

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.