Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index autoincrement for Microsoft SQL Server 2008 R2

I created a new table in SQL Server 2008 R2, and i would like that the index is on autoincrement. How to do that? There is no identity data type; i selected int

like image 241
Magnetic_dud Avatar asked Nov 19 '10 18:11

Magnetic_dud


People also ask

How do I get Autoincrement ID?

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) .

What is Autoincrement in SQL?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can change primary key to auto increment in SQL Server?

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.


2 Answers

In SQL Server, it's not a separate datatype ("autoincrement") - but you can define an INT column to be an IDENTITY.

How are you creating your table - visual designer or T-SQL script??

In T-SQL, you would use:

CREATE TABLE dbo.MyTable(ID INT IDENTITY(1,1) ......

and in the visual table designer, you need to check:

alt text

It's an option for a column of type INT - you can define the seed (starting value) and the increment - typically both are set to 1.

like image 84
marc_s Avatar answered Oct 11 '22 20:10

marc_s


If your table definition is like this,

....,
@id int,
....

change it to,

....
@id int identity(1,1),
....

This will create an identity column which starts id with 1 and keeps increasing it by one(i.e. step) as each record in the table is inserted.

like image 42
Srinivas Reddy Thatiparthy Avatar answered Oct 11 '22 22:10

Srinivas Reddy Thatiparthy