1

I have a column in my database. How do i insert an incremented number via an insert so it fills it every row?

PriceCheaperton
  • 5,071
  • 17
  • 52
  • 94

6 Answers6

8

Use Identity column

Suppose you want Column Id to be incremented automatically a row is inderted define it as identity

ID INT IDENTITY (1,1)

First 1 is starting value second 1 is seeding it means increment by which integer

in this case the value will start at 1 and increment by 1 every time u insert a new row.

Please let me know if any further help needed

Nenad Zivkovic
  • 18,221
  • 6
  • 42
  • 55
Ashutosh Arya
  • 1,138
  • 2
  • 8
  • 14
3

You may go to the designer of the table add a new Column and then go to the properties tab for the column and set

Identity Specification

  • IsIdentity :Yes
  • Identity Increment : 1
  • Identity Seed : 1

Identity Increment sets the number that will be added each time you insert a row. If it was 10 then you would have ids like 10, 20, 30.

Identity Seed is an offset you may need to add (which is the first number to appear) If it was 10 then your first Id would be 10.

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
2

Set identity seed for the column you want to increment the value

Alter Table Names Add Id_new Int Identity(1, 1) Go

Alter Table Names Drop Column ID Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'
Your father
  • 97
  • 1
  • 11
1

When creating a new table, set the Data Type field to int and de-select Allow Nulls for that column.

Then, in column Properties, expand Identity Specification and change (Is Identity) to Yes.

By default the Identity Increment should be set to 1.

JsonStatham
  • 9,770
  • 27
  • 100
  • 181
0

Make that column identity while creating the table which will auto increment that column for each row. You don't have to do explicit insert.

hima
  • 610
  • 3
  • 10
  • 24
0

Create auto increment for that column for example

CREATE TABLE table_name
            (
             id int NOT NULL IDENTITY (1, 1),
             name varchar(50) NULL
            )  ON [PRIMARY]

In the above example column id is auto increment. After each insert its value will increment by 1.

If you want to change that increment number later, please check

Reset AutoIncrement in SQL Server after Delete

Community
  • 1
  • 1
Fathah Rehman P
  • 8,401
  • 4
  • 40
  • 42