Upon executing I keep receiving the error:
Cannot insert the value NULL into column ‘ExampleID’, table ‘DB_Example.dbo.tbl_Example’; column does not allow nulls. INSERT fails.
However I don’t think any NULL values are present. I am trying to simply fill a table with specific values by using the following:
SELECT * FROM tbl_Example INSERT INTO tbl_Example ([Name]) VALUES ('Example1'), ('Example2'), ('Example3'), ('Example4')
I am using the exact same code/format to fill 3 other tables in the database and do not receive an error for any of them besides this one. Cannot figure it out.
Edit: DBMS is SQL Server
Advertisement
Answer
The problem is that columns not included in the INSERT
are set to their default values. The default “default” is NULL
, which is why you are getting your error.
Check your definition of Example
. Normally, a column called ExampleId
would be an identity column. So, it should look like:
CREATE TABLE tbl_Example ( ExampleId INT IDENTITY(1, 1) PRIMARY KEY, Name VARCHAR(?) );
The IDENTITY()
serves as a default value. It is a generally increasing sequence of values, based on insertion order.
With this definition, your code will work:
INSERT INTO tbl_Example ([Name]) VALUES ('Example1'), ('Example2'), ('Example3'), ('Example4');
I would not recommend explicitly inserting the values of a primary key. There are some situations where you want to do that, but as a general rule, automatically generating keys is preferable (if you want to avoid errors on inserts).