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

前端 未结 13 1258
鱼传尺愫
鱼传尺愫 2020-11-27 05:35

I\'m using the following query:

INSERT INTO role (name, created) VALUES (\'Content Coordinator\', GETDATE()), (\'Content Viewer\', GETDATE())
相关标签:
13条回答
  • 2020-11-27 06:05

    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.

    0 讨论(0)
  • 2020-11-27 06:13

    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.

    0 讨论(0)
  • 2020-11-27 06:14

    if use entityframework. open migration, set value nullable: true, and update database

    enter image description here

    0 讨论(0)
  • 2020-11-27 06:15

    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
    )
    )
    
    0 讨论(0)
  • 2020-11-27 06:15

    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.

    0 讨论(0)
  • 2020-11-27 06:16

    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())
    
    0 讨论(0)
提交回复
热议问题