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.
asked Apr 4, 2012 at 14:33
0
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
andIndentity Increment=1
answered Apr 4, 2012 at 14:36
CurtisCurtis
101k65 gold badges269 silver badges351 bronze badges
3
use IDENTITY(1,1)
while creating the table
eg
CREATE TABLE SAMPLE(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,
CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)
Nick
1,1583 gold badges24 silver badges36 bronze badges
answered Jan 9, 2018 at 19:41
If the id
column has no default value, but has NOT NULL
constraint, then you have to provide a value yourself
INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())
answered Apr 4, 2012 at 14:40
Andy IrvingAndy Irving
2,6571 gold badge14 silver badges11 bronze badges
Encountered the same issue. This is something to do with your table creation. When you created table you have not indicate ‘ID
‘ column to be Auto Increment
hence you get this error. By making the column Primary Key
it cannot be null
or contain duplicates hence without Auto Increment
pretty obvious to throw column does not allow nulls. INSERT fails
.
There are two ways you could fix this issue.
1). via MS SQL Server Management Studio
-
Got to MS SQL Server Management Studio
-
Locate your table and right click and select Design
-
Locate your column and go to Column Properties
-
Under Indentity Specification: set (Is Identity)=Yes and Indentity
Increment=1
2). via ALTER SQLs
ALTER TABLE table DROP COLUMN id; // drop the existing ID
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key
answered Dec 15, 2022 at 7:02
Du-LacosteDu-Lacoste
11.3k2 gold badges67 silver badges50 bronze badges
0
You either need to specify an ID in the insert, or you need to configure the id column in the database to have Identity Specification = Yes.
answered Apr 4, 2012 at 14:38
JupiterP5JupiterP5
3181 silver badge10 bronze badges
As id is PK it MUST be unique and not null.
If you do not mention any field in the fields list for insert it’ll be supposed to be null or default value.
Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.
answered Apr 4, 2012 at 14:38
quzaryquzary
2851 silver badge4 bronze badges
You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.
answered Apr 4, 2012 at 14:44
you didn’t give a value for id. Try this :
INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())
Or you can set the auto increment on id field, if you need the id value added automatically.
answered May 9, 2017 at 2:04
I had a similar problem and upon looking into it, it was simply a field in the actual table missing id
(id
was empty/null
) — meaning when you try to make the id
field the primary key
it will result in error because the table contains a row with null
value for the primary key
.
This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.
answered Nov 1, 2019 at 15:22
WARNING! Make sure the target table is locked when using this method
(As per @OnurOmer’s comment)
if you can’t or don’t want to set the autoincrement property of the id, you can set value for the id for each row like this:
INSERT INTO role (id, name, created)
SELECT
(select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
, name
, created
FROM (
VALUES
('Content Coordinator', GETDATE())
, ('Content Viewer', GETDATE())
) AS x(name, created)
answered Apr 16, 2018 at 2:13
robotikrobotik
1,8081 gold badge20 silver badges25 bronze badges
2
RULE: You cannot IGNORE those colums that do not allow null values, when inserting new data.
Your Case
- You’re trying to insert values, while ignoring the
id
column, which does not allow nulls. Obviously this won’t work. - Gladly for you the «Identity Specification» seems to automatically fill the not nullable
id
values for you (see selected answer), when you later execute the insert query.
My Case
- The problem (while using SSMS): I was having this error when trying to add a new non-nullable column to an already existing table with data. The error I’d got was:
Cannot insert the value NULL into column ‘id_foreign’, table ‘MyDataBase.dbo.Tmp_ThisTable’; column does not allow nulls. INSERT fails.
The statement has been terminated.
- The solution:
- I created the column I needed
id_foreign
, allowing nulls. - I edited/inserted all the required values for
id_foreign
. - Once the values where in place, I went back and unchecked the «Allow Nulls» checkbox. Now the error was gone.
- I created the column I needed
answered Jul 26, 2022 at 14:54
carloswm85carloswm85
1,25813 silver badges21 bronze badges
- Remove From My Forums
-
Question
-
N0ob here.
This error message keeps getting generated when i try to submit a particular form on my site. This used to work fine until i changed servers and exported my database to the new server. As far as i can tell everything is fine but then again, like i said, i’m a total newbie so i’m not seeing something i’m sure…
Here is the full Error message..
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column ‘ReviewID’, table ‘reviews.dbo.OR_Comments’; column does not allow nulls. INSERT fails.
The statement has been terminated.Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Cannot insert the value NULL into column 'ReviewID', table 'reviews.dbo.OR_Comments'; column does not allow nulls. INSERT fails. The statement has been terminated.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1005 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +149 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +404 System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +447 System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +72 System.Web.UI.WebControls.DetailsView.HandleInsert(String commandArg, Boolean causesValidation) +390 System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +602 System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e) +95 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e) +109 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +115 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +132 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
Any help appreciated!
Answers
-
Here’s what you should be paying attention to:
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column ‘ReviewID’, table ‘reviews.dbo.OR_Comments’; column does not allow nulls. INSERT fails.
The statement has been terminated.This means that ReviewID column of OR_Comments table doesn’t allow NULL values. You should either:
-
Allow NULL values to be inserted in this column
-
Configure your data source not to insert anything in this column and let server generate the value (if this is an identity column)
-
-
You can allow NULLs on the table by using Management Studio. Right click on the table and choose design, and check the box under the «Allow Nulls» next to the column name you want to allow nulls on.
If you are a developer, you might have come across the ‘Cannot insert the value NULL into column’ error while working on databases. This error can be frustrating, but it is not uncommon. In this technical guide, we will provide you with step-by-step solutions to fix this error.
What Causes the ‘Cannot Insert the Value Null into Column’ Error?
This error occurs when you try to insert a null value into a column that does not allow null values. Here are some possible causes of this error:
- The column in the database table is set to not allow null values, and you are trying to insert a null value into that column.
- The column does not exist in the table, or you misspelled the column name.
- The data type of the value you are trying to insert does not match the data type of the column.
- There is a trigger on the table that is preventing the insert of the null value.
How to Fix the ‘Cannot Insert the Value Null into Column’ Error
Here are some steps you can take to fix the ‘Cannot Insert the Value Null into Column’ error:
- Check the Column Definition
Make sure that the column in the database table is set to allow null values. If it is not, you will need to modify the column definition to allow null values. You can do this using the ALTER TABLE statement:
ALTER TABLE table_name ALTER COLUMN column_name datatype NULL;
Replace table_name
with the name of your table, column_name
with the name of the column you want to modify, and datatype
with the data type of the column.
- Check the Column Name
Make sure that the column name you are trying to insert into exists in the table, and that you have spelled it correctly.
- Check the Data Type
Make sure that the data type of the value you are trying to insert matches the data type of the column. If they do not match, you will need to convert the data type of the value to match the data type of the column. You can do this using the CAST or CONVERT function:
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, CONVERT(datatype, value2), value3);
Replace table_name
with the name of your table, column1
, column2
, and column3
with the names of the columns you want to insert values into, value1
, value2
, and value3
with the values you want to insert, and datatype
with the data type of the column.
- Check for Triggers
If there is a trigger on the table that is preventing the insert of the null value, you will need to modify the trigger to allow the insert of null values. You can do this using the ALTER TRIGGER statement:
ALTER TRIGGER trigger_name ON table_name
AFTER INSERT, UPDATE
AS
BEGIN
-- trigger logic here
END;
Replace trigger_name
with the name of your trigger, and table_name
with the name of your table.
FAQ
Q1. What is a null value in SQL?
A null value in SQL represents a missing or unknown value. It is not the same as zero or an empty string.
Q2. Can I insert a null value into a column that allows nulls?
Yes, you can insert a null value into a column that allows nulls. You do not need to specify a value for that column when you insert a new row.
Q3. Can I modify a column to allow nulls if it already contains data?
Yes, you can modify a column to allow nulls even if it already contains data. However, you will need to update the existing data to set the column to null if it does not already have a value.
Q4. What is a trigger in SQL?
A trigger in SQL is a special type of stored procedure that is automatically executed in response to certain events, such as the insertion, deletion, or modification of data in a table.
Q5. Can I disable a trigger temporarily?
Yes, you can disable a trigger temporarily using the DISABLE TRIGGER statement:
DISABLE TRIGGER trigger_name ON table_name;
Replace trigger_name
with the name of your trigger, and table_name
with the name of your table.
- SQL Server Insert
- SQL Server Data Types
- SQL Server Triggers
SQL Server Error Messages — Msg 515 Error Message Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Column Name', table 'Table Name'; column does not allow nulls. INSERT fails. The statement has been terminated. Causes: As the message suggests, you are trying to insert a new record into a table and one of the columns is being assigned a NULL value but the column does not allow NULLs. |
To illustrate, let’s say you have the following table definitions:
CREATE TABLE [dbo].[Users] ( [UserName] VARCHAR(10) NOT NULL, [FullName] VARCHAR(100) NOT NULL, [Email] VARCHAR(100) NOT NULL, [Password] VARCHAR(20) NOT NULL, [CreationDate] DATETIME NOT NULL DEFAULT(GETDATE()) )
There are three ways that the error can be encountered. The first way is when a column is not specified as one of the columns in the INSERT clause and that column does not accept NULL values.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com' )
Given this INSERT statement, the [Password] column is not specified in the column list of the INSERT INTO clause. Since it is not specified, it is assigned a value of NULL. But since the column does not allow NULL values, the following error is encountered:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Password', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
The second way that the error can be encountered is when a NULL value is explicitly assigned to the column that does not allow NULLs.
INSERT INTO [dbo].[Users]([UserName], [FullName], [Email], [Password]) VALUES ( 'MICKEY', 'Mickey Mouse', NULL, 'Minnie' )
As can be seen from this INSERT command, the [Email] column is being assigned a NULL value during the insert but since the column does not allow NULL values, the following error is generated:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Email', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
The third possible way that the error is encountered is similar to the second one, which is by explicitly assigning a NULL value to a column, as shown below:
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', NULL )
The only difference is that the column being assigned to has a default value (in this case, the default value of the [CreationDate] column is current system date and time as generated by the GETDATE() function). Since the column has a default value, you would think that if a NULL value is assigned to it, it will assign the default value instead. However, the following error is encountered:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'CreationDate', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
Solution / Work Around:
Regardless of the way on how the error is encountered, if a column does not accept NULL values, always assign a value to it when inserting new records to the table.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', GETDATE() )
If the column does not accept NULL values but has a default value assigned to it and you want that the default value be used for the newly inserted record, just do not include that column in the INSERT statement and the default will automatically be assigned to the column.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie' )
In this example, since the [CreationDate] column has a default value of GETDATE(), since it is not included in the column list in the INSERT INTO clause, the default value gets assigned to the column.
Another way of explicitly assigning the default value is by using the reserved word DEFAULT in the VALUES list, as can be seen in the following:
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', DEFAULT )
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.
asked Apr 4, 2012 at 14:33
0
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
andIndentity Increment=1
answered Apr 4, 2012 at 14:36
CurtisCurtis
100k65 gold badges267 silver badges349 bronze badges
3
use IDENTITY(1,1)
while creating the table
eg
CREATE TABLE SAMPLE(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,
CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)
Nick
1,1583 gold badges26 silver badges35 bronze badges
answered Jan 9, 2018 at 19:41
If the id
column has no default value, but has NOT NULL
constraint, then you have to provide a value yourself
INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())
answered Apr 4, 2012 at 14:40
Andy IrvingAndy Irving
2,6371 gold badge14 silver badges11 bronze badges
Encountered the same issue. This is something to do with your table creation. When you created table you have not indicate ‘ID
‘ column to be Auto Increment
hence you get this error. By making the column Primary Key
it cannot be null
or contain duplicates hence without Auto Increment
pretty obvious to throw column does not allow nulls. INSERT fails
.
There are two ways you could fix this issue.
1). via MS SQL Server Management Studio
-
Got to MS SQL Server Management Studio
-
Locate your table and right click and select Design
-
Locate your column and go to Column Properties
-
Under Indentity Specification: set (Is Identity)=Yes and Indentity
Increment=1
2). via ALTER SQLs
ALTER TABLE table DROP COLUMN id; // drop the existing ID
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key
answered Dec 15, 2022 at 7:02
Du-LacosteDu-Lacoste
10.7k2 gold badges63 silver badges50 bronze badges
You either need to specify an ID in the insert, or you need to configure the id column in the database to have Identity Specification = Yes.
answered Apr 4, 2012 at 14:38
JupiterP5JupiterP5
3081 silver badge10 bronze badges
As id is PK it MUST be unique and not null.
If you do not mention any field in the fields list for insert it’ll be supposed to be null or default value.
Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.
answered Apr 4, 2012 at 14:38
quzaryquzary
2851 silver badge4 bronze badges
You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.
answered Apr 4, 2012 at 14:44
you didn’t give a value for id. Try this :
INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())
Or you can set the auto increment on id field, if you need the id value added automatically.
answered May 9, 2017 at 2:04
I had a similar problem and upon looking into it, it was simply a field in the actual table missing id
(id
was empty/null
) — meaning when you try to make the id
field the primary key
it will result in error because the table contains a row with null
value for the primary key
.
This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.
answered Nov 1, 2019 at 15:22
WARNING! Make sure the target table is locked when using this method
(As per @OnurOmer’s comment)
if you can’t or don’t want to set the autoincrement property of the id, you can set value for the id for each row like this:
INSERT INTO role (id, name, created)
SELECT
(select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
, name
, created
FROM (
VALUES
('Content Coordinator', GETDATE())
, ('Content Viewer', GETDATE())
) AS x(name, created)
answered Apr 16, 2018 at 2:13
robotikrobotik
1,7741 gold badge19 silver badges24 bronze badges
2
RULE: You cannot IGNORE those colums that do not allow null values, when inserting new data.
Your Case
- You’re trying to insert values, while ignoring the
id
column, which does not allow nulls. Obviously this won’t work. - Gladly for you the «Identity Specification» seems to automatically fill the not nullable
id
values for you (see selected answer), when you later execute the insert query.
My Case
- The problem (while using SSMS): I was having this error when trying to add a new non-nullable column to an already existing table with data. The error I’d got was:
Cannot insert the value NULL into column ‘id_foreign’, table ‘MyDataBase.dbo.Tmp_ThisTable’; column does not allow nulls. INSERT fails.
The statement has been terminated.
- The solution:
- I created the column I needed
id_foreign
, allowing nulls. - I edited/inserted all the required values for
id_foreign
. - Once the values where in place, I went back and unchecked the «Allow Nulls» checkbox. Now the error was gone.
- I created the column I needed
answered Jul 26, 2022 at 14:54
carloswm85carloswm85
1,05410 silver badges20 bronze badges
SQL Server Error Messages — Msg 515 Error Message Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Column Name', table 'Table Name'; column does not allow nulls. INSERT fails. The statement has been terminated. Causes: As the message suggests, you are trying to insert a new record into a table and one of the columns is being assigned a NULL value but the column does not allow NULLs. |
To illustrate, let’s say you have the following table definitions:
CREATE TABLE [dbo].[Users] ( [UserName] VARCHAR(10) NOT NULL, [FullName] VARCHAR(100) NOT NULL, [Email] VARCHAR(100) NOT NULL, [Password] VARCHAR(20) NOT NULL, [CreationDate] DATETIME NOT NULL DEFAULT(GETDATE()) )
There are three ways that the error can be encountered. The first way is when a column is not specified as one of the columns in the INSERT clause and that column does not accept NULL values.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com' )
Given this INSERT statement, the [Password] column is not specified in the column list of the INSERT INTO clause. Since it is not specified, it is assigned a value of NULL. But since the column does not allow NULL values, the following error is encountered:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Password', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
The second way that the error can be encountered is when a NULL value is explicitly assigned to the column that does not allow NULLs.
INSERT INTO [dbo].[Users]([UserName], [FullName], [Email], [Password]) VALUES ( 'MICKEY', 'Mickey Mouse', NULL, 'Minnie' )
As can be seen from this INSERT command, the [Email] column is being assigned a NULL value during the insert but since the column does not allow NULL values, the following error is generated:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'Email', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
The third possible way that the error is encountered is similar to the second one, which is by explicitly assigning a NULL value to a column, as shown below:
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', NULL )
The only difference is that the column being assigned to has a default value (in this case, the default value of the [CreationDate] column is current system date and time as generated by the GETDATE() function). Since the column has a default value, you would think that if a NULL value is assigned to it, it will assign the default value instead. However, the following error is encountered:
Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'CreationDate', table 'SQLServerHelper.dbo.Users'; column does not allow nulls. INSERT fails. The statement has been terminated.
Solution / Work Around:
Regardless of the way on how the error is encountered, if a column does not accept NULL values, always assign a value to it when inserting new records to the table.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', GETDATE() )
If the column does not accept NULL values but has a default value assigned to it and you want that the default value be used for the newly inserted record, just do not include that column in the INSERT statement and the default will automatically be assigned to the column.
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie' )
In this example, since the [CreationDate] column has a default value of GETDATE(), since it is not included in the column list in the INSERT INTO clause, the default value gets assigned to the column.
Another way of explicitly assigning the default value is by using the reserved word DEFAULT in the VALUES list, as can be seen in the following:
INSERT INTO [dbo].[Users] ( [UserName], [FullName], [Email], [Password], [CreationDate] ) VALUES ( 'MICKEY', 'Mickey Mouse', 'mickeymouse@disney.com', 'Minnie', DEFAULT )
- Remove From My Forums
-
Question
-
hello anyone..can u guys help me sove this prob?? Cannot insert the value NULL into column ‘ID’, table ‘C:USERSADURADOCUMENTSVISUAL STUDIO 2010WEBSITESWEBSITE3APP_DATADATABASE.MDF.dbo.pentadbiradd’; column does not allow nulls. INSERT fails. The
statement has been terminated. i got confusing ….the column ID in my pentadbiradd table are all filled with the data … and i set the id column as a primary key and untick the allow null.. actually ,what the problem.. i think i done correctly regarding
my db… urgently need help… thanks- Moved by
Saturday, December 24, 2011 8:43 PM
Moved to a more appropriate forum for best response (From:.NET Framework inside SQL Server)
- Moved by
Answers
-
The solution is simple: INSERT a value into that «not null» column. Alternately, you can place a default constraint on the column.
Example:
CREATE TABLE test (ID INT NOT NULL, Celebrity varchar(32) NOT NULL, CreateDate datetime default (CURRENT_TIMESTAMP)); GO -- Following will give error INSERT test (Celebrity) SELECT 'Elvis Presley' /* Msg 515, Level 16, State 2, Line 3 Cannot insert the value NULL into column 'ID', table 'tempdb.dbo.test'; column does not allow nulls. INSERT fails. The statement has been terminated. */ -- Following will work INSERT test (ID, Celebrity) SELECT 1, 'Elvis Presley' -- (1 row(s) affected)
Kalman Toth, SQL Server & Business Intelligence Training; SQL SERVER GRAND SLAM
- Edited by
Kalman Toth
Saturday, December 24, 2011 9:26 PM - Marked as answer by
KJian_
Friday, December 30, 2011 5:25 AM
- Edited by
No no no no no. Do not drop the constraint for any reason at this point. This is an entirely bad suggestion and one that is not appropriate for someone without significant experience with both tsql and with your system (and how it is implemented).
As I mentioned before, your problem is data related. It might also be logic related — that is, there is an assumption built into the logic about what your data looks like, how many rows are affected or retrieved with any particular query, what is or
can be null, etc. You need to take the failing situation line by line through the procedure logic and determine which statement is actually failing and why it is attempting to insert a row (or rows!) with values that cause the insert to fail. Since
your procedure executes other procedures, you may find that the source of the error lies in one of these.
And another suggestion — do not make too many changes at one time without fully understanding them. You were advised to do something like this
,ISNULL(@ToRowPointer,’00000000-0000-0000-0000-000000000000′)
When you do this, you need to understand the ramifications. This means that you are provided a completely bogus identifier to cover-up the problem you are currently experiencing. So what code uses this value? And what will happen when this
code finds your new bogus value and attempts to use it (since it is not null but does not actually refer to anything) if it attempts to «look up» the value somewhere? Your system breaks. And now there is another potential issue because
you have changed some of your logic. Here is another script to demonstrate the change. It relates back to your use of @@ROWCOUNT to determine if anything was «done» in the previous statement. Using SET will always set @@rowcount to 1.
So when your query selects no rows, SET will store a NULL value in your variable whereas SELECT will leave it unchanged. This is an important distinction.
set nocount on; declare @x int declare @table table (id int); set @x = 3; select top 1 @x = id from @table; select 'select version, no rows', @@ROWCOUNT rcount, @x [@x]; set @x = (select top 1 id from @table); select 'set version, no rows', @@ROWCOUNT rcount, @x [@x]; insert @table (id) values (10), (4); select top 1 @x = id from @table; select 'select version, 2 rows', @@ROWCOUNT rcount, @x [@x]; set @x = (select top 1 id from @table); select 'set version, 2 rows', @@ROWCOUNT rcount, @x [@x];
However, I suggest you do back to your original code. Add select statements to the procedure (or a debugging copy) and select the variables that used in the failing statement — put this immediately before the failing statement so you can see them when it
runs. Gradually work your way backwards through the logic until you understand why the failing statement fails. Effectively, how does that variable become null (or is it ever set correctly)? Be careful — because the code relies on @@ROWCOUNT (which
I recommend you change eventually to remove this error-prone logic).
And one last suggestion as a general debugging method. Convert your procedure into a script that you can run over and over. Remove the «create procedure» part and simply define the procedure arguments as local variables. Assign
them the values you provide to the procedure’s parameters. You should start with a begin transaction statement and end with a rollback transaction statement — this allows you to run the script over and over without committing any changes. Using
a script you can comment out the bulk of the code and iteratively run it. For each run you can uncomment a line or two to see the effects of the additional logic. Eventually you will figure out how that NULL value gets into your variable.
- Marked as answer by
Monday, September 28, 2015 8:19 PM
Ошибка при обновлении базы |
Я |
Mad88
23.01.17 — 12:19
Добрый день Ут 10.3.37.2
Платформа 8.3.9.1818
При обновлении базы выдает ошибку
В процессе обновления информационной базы произошла критическая ошибка
по причине:
Ошибка СУБД:
Microsoft SQL Server Native Client 11.0: Cannot insert the value NULL into column ‘_Fld426’, table ‘trd_zubr_bd.dbo._Reference27NG’; column does not allow nulls. INSERT fails.
HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1.
База не типовая, обновление с релиза 37.2 до 39.1. Ошибка появляется именно в момент обновления.
Господин ПЖ
1 — 23.01.17 — 12:20
все ж написано
Cannot insert the value NULL into column
Serg_1960
2 — 23.01.17 — 12:21
ТиИ?
Mad88
3 — 23.01.17 — 12:31
(1) То есть если он не может вставить, мне вставить за него или что? Конкретные предложения будут?
Господин ПЖ
4 — 23.01.17 — 12:32
>мне вставить за него или что?
тебя он тоже пошлет
Serg_1960
5 — 23.01.17 — 12:36
(1) Между прочим (правда стоит добавить: маловероятно, но возможно) такая же ошибка может появиться после сбоя во время обновления конфигурации, когда в таблице SQL остается поле, уже удаленное в конфигураторе 1С.
(3) Куда уж «конкретнее» Я спросил «ТиИ делал?» Нет? Сделай.
Ёпрст
6 — 23.01.17 — 12:37
(0) Ну посмотри, че за справочник, для начала. И чего он там нулл туда инсёртит
Mad88
7 — 23.01.17 — 13:18
(5) Какие там галочки надо ставить?)
Господин ПЖ
8 — 23.01.17 — 13:19
логическая+физическая
Господин ПЖ
9 — 23.01.17 — 13:20
ругается на справочник — п.э. всякие «итоги» не нужны
Mad88
10 — 23.01.17 — 13:21
Ставил все кроме «Пересчет итогов», ошибка осталась
Господин ПЖ
11 — 23.01.17 — 13:22
кэш продувал? что за поле, почему у тебя судя по всему по разному поле описывается на уровне субд и конфигурации?
Mad88
12 — 23.01.17 — 13:38
(11) Кэш чистиль…)
Serg_1960
13 — 23.01.17 — 21:36
Такая ошибка ещё бывает, когда ТиИ создало объекты при обнаружении «битых» ссылок — оно могло забить в базу «пустые» записи и платформа при обновлении сама же об них спотыкается.
Используя ПолучитьСтруктуруХраненияБазыДанных(), определи наименования справочника Reference27 и реквизита _Fld426; запросом найди записи со значением NULL в этом реквизите и удали их (или исправь, заполнив нужными значениями).
PS: а вообще, в принципе, Господин ПЖ прав, — очень подозрительное соответствие имени поля и таблицы, не стандартное для 1С
суперйцукен
14 — 23.01.17 — 21:42
(13) На самом деле очень интересно давать полям, переменным, реквизитам наименования типа «Документ», «справочник», «Дата»…
Mad88
15 — 24.01.17 — 09:38
Помогло решение из (13).Проблема оказалась со справочником банковские счета, было 2 элемента с не заполненными номерами счетов.
This question follows the answer of my other question there:
Insert with OUTPUT correlated to sub query table
The Person.LastName column has a NOT NULL constraint. When I execute this code:
CREATE TABLE tempIDs
( PersonId INT,
FinancialInstitutionId INT
);
MERGE INTO Person
USING FinancialInstitution AS fi
ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (CreationDate, AdministrativeStatus, LastName, Street1, Number1, City1, State1, PostCode1, CountryId1, WorkDirectPhone1, Fax1, Email1)
VALUES (GetDate(), 'Legal', fi.Name, fi.Street, fi.Number, fi.City, fi.[State], fi.PostCode, fi.CountryId, fi.PhoneNumber, fi.Fax, fi.Email)
OUTPUT inserted.Id, fi.Id INTO tempIDs;
UPDATE fi
SET fi.PersonId = t.PersonId
FROM FinancialInstitution AS fi
JOIN tempIDs AS t
ON fi.Id = t.FinancialInstitutionId ;
I get the following error:
Cannot insert the value NULL into column 'LastName', table 'Person'; column does not allow nulls. UPDATE fails.
The thing is that there is no FinancialInstitution.Name that is NULL.
SELECT Name FROM FinancialInstitution WHERE Name = NULL
This returns no row. Beside, if I replace fi.Name with a value (‘A Last Name’) the request works.