Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

Tags:

sql

sql-server

I'm using the following query:

INSERT INTO role (name, created) VALUES ('Content Coordinator', GETDATE()), ('Content Viewer', GETDATE()) 

However, I'm not specifying the primary key (which is id). So my questions is, why is sql server coming back with this error:

Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'id', table 'CMT_DEV.dbo.role'; column does not allow nulls. INSERT fails. The statement has been terminated. 
like image 940
Webnet Avatar asked Apr 04 '12 14:04

Webnet


People also ask

How do you insert NULL values in a column in SQL?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);

Can not insert NULL value?

You cannot insert NULL values in col1 and col2 because they are defined as NOT NULL. If you run the script as is, you will receive an error. To fix this code, replace NULL in the VALUES part with some values (for example, 42 and 'bird' ).

Can you insert a NULL value in SQL?

The SQL INSERT statement can also be used to insert NULL value for a column.


1 Answers

I'm assuming that id is supposed to be an incrementing value.

You need to set this, or else if you have a non-nullable column, with no default value, if you provide no value it will error.

To set up auto-increment in SQL Server Management Studio:

  • Open your table in Design
  • Select your column and go to Column Properties
  • Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1
like image 69
Curtis Avatar answered Oct 23 '22 11:10

Curtis