Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

script to add and remove auto-increment property from a column

Tags:

For a sql script I'm working on, I need to programmatically remove the identity, identity seed, and identity increment for a column in an existing table, then add them back to the table at the end of the script. Does anyone have a reference or an example on how to do this?

like image 628
quillbreaker Avatar asked Oct 01 '10 17:10

quillbreaker


People also ask

How do I add an auto increment to an existing column?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

How can add auto increment to column in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How can insert auto increment value in SQL query?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.


2 Answers

You should do this:

SET IDENTITY_INSERT <TableName> ON
-- Do the inserting in the table with name <TableName>
SET IDENTITY_INSERT <TableName> OFF

For more details look in the MSDN.

like image 145
Ivan Ferić Avatar answered Sep 29 '22 07:09

Ivan Ferić


Yes, you just do this:

SET IDENTITY_INSERT [TABLE] ON

And then back on:

SET IDENTITY_INSERT [TABLE] OFF

This will allow you to enter manual data in the identity column.

http://msdn.microsoft.com/en-us/library/ms188059.aspx

like image 45
Dustin Laine Avatar answered Sep 27 '22 07:09

Dustin Laine