Boldijar Paul
Boldijar Paul

Reputation: 5495

C# SQL create table with autonumber column

How can I create a table from SQL Command that will have a ID that is auto-number or auto-increment?

 SqlCommand com 
   = new SqlCommand("create table VeryCoolTable(\"Name\" nvarchar(50) 
      ,id AUTONUMBER)", con);

The counter is not recognized and I get error.

Upvotes: 2

Views: 6853

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

if you are using SQL-Server it is called IDENTITY

ID int IDENTITY(1,1)    

1. first argument is the starting value
2. second argument is incrementing count

if you want to start the value from 500 and increment it by 5 then try this:

ID int IDENTITY(500,5)    

Solution 1:

SqlCommand com = new SqlCommand("create table VeryCoolTable(\"Name\"
                                    nvarchar(50),ID int IDENTITY(1,1))", con);

Note: i would suggest you to declare the ID column as PRIMARY KEY to identify the records in your table uniqly.

Solution 2

SqlCommand com = new SqlCommand("create table VeryCoolTable(\"Name\"
                     nvarchar(50),ID int IDENTITY(1,1) PRIMARY KEY)", con);

Upvotes: 8

Magnus Ahlin
Magnus Ahlin

Reputation: 655

CREATE TABLE Persons
(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Upvotes: 2

Related Questions