views:

1393

answers:

3

I have a table that has a forced auto increment column and this column is a very valuable ID that is retained through out the entire app. Sorry to say it was poor development on my part to have this be the auto incrementing column.

So, here is the problem. I have to insert into this table an ID for the column that has already been created and removed from the table. Kind of like resurrecting this ID and putting it back into the table.

So how can I do this programatically do this without turning the column increment off. Correct me if I am wrong, if I turn it off programatically, It will restart at 0 or 1 and I don't want that to happen...

+4  A: 

If you are in Microsoft SQL Server, you can "turn off" the autoIncrementing feature by issuing the statement

  Set Identity_Insert [TableName] On
  -- -----------------------------------------
  Insert TableName (pkCol, [OtherColumns]
  Values(pkValue, [OtherValues])
  -- ---- Don't forget to turn it back off ----
  Set Identity_Insert [TableName] Off
Charles Bretana
Thanks, @jvanderh, I edited to clarify
Charles Bretana
Isn't this just backwards?? I am under the impression you have to SET IDENTITY_INSERT *ON* in order to be able to insert a specified value into an IDENTITY column, and then afterwards you have to turn if OFF again.....
marc_s
marc_s is right...you have it backwards
jvanderh
Does it keep the last number for the incremented Identity? I don't want it to reset the entire Identity column it self...
Scott
thanks again, I am editing to correct
Charles Bretana
And @Scott, Yes, it "keeps" the old value... i.e., this prcoess does not affect the "current" value t obe used for the next auto-increment Identity...
Charles Bretana
+3  A: 

In addition to Charles' answer (which is now 100% correct :-) and which preserves the current value of the IDENTITY on the table), you might also want to check the current value of an IDENTITY on a table - you can do this with this command here:

DBCC CHECKIDENT('YourTableName')

If you ever need to actually change it, you can do so by using this command here:

DBCC CHECKIDENT ('YourTableName', RESEED, (new value for IDENTITY) )

Cheers!
Marc

marc_s
A: 

Does anyone have any clue how this can be achieved using MySQL? I am in the same situation.

Cristi Cotovan
It's been about 5 years since I've used MySQL, but I think MySQL will only autoincrement if you do not specify the primary key column in your insert statement. That said, you'd be better off asking this as its own question rather than as a reply to this question.
Randolpho