I started to use SQL Server recently and I still don't know the best way to do some things.
I created all the tables with a column ID as the primary key. Now when I try to insert values I get the following error:
"Cannot insert the value NULL into column 'id', table 'Project.dbo.Table'; column does not allow nulls. INSERT fails. The statement has been terminated."
What is a good, simple solution to this problem?
Best Answer
If your table is empty, you can drop and recreate the table again and add
IDENTITY(1,1)
to the column definition ofid
to make yourid
column inProject.dbo.Table
auto increment.Something like this.
You can either add
PRIMARY KEY
with the column name like thisid int IDENTITY(1,1) NOT NULL PRIMARY KEY,
or at the end after defining all columns like thisCONSTRAINT PK_Table PRIMARY KEY(id)
SQL Server does not allow you to add
IDENTITY
by altering a table. useGO
betweenIF EXISTS ...DROP TABLE
and theCREATE TABLE
statements to run those statements in separate batches.