简体   繁体   中英

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.

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);
CREATE TABLE Persons
(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM