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

前端 未结 13 1261
鱼传尺愫
鱼传尺愫 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:20

    In my case,

    I was trying to update my model by making a foreign key required, but the database had "null" data in it already in some columns from previously entered data. So every time i run update-database...i got the error.

    I SOLVED it by manually deleting from the database all rows that had null in the column i was making required.

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

    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.

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

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

    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.

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

    You can insert a value manually in the ID column (here I call it "PK"):

    insert into table1 (PK, var1, var2)
    values ((select max(PK)+1 from table1), 123, 456)
    
    0 讨论(0)
  • 2020-11-27 06:29

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