SQL Server, can't insert null into primary key field?

后端 未结 8 587
野趣味
野趣味 2020-12-03 10:46

I\'m about ready to rip my hair out on this one. I\'m fairly new to MS SQL, and haven\'t seen a similar post anywhere.

When I try to do a statement like this:

<
相关标签:
8条回答
  • 2020-12-03 11:22

    Primary Key fields cannot contain null values in MS SQL. If you want to populate a SQL table and dont know what to enter for a integer based primary key field then set the pk to an Identity field. Also when specifying Insert statements its wise to use the column mapping portion of the insert statment for example:

    Insert into (field1, field2, field3)
    values
    (value1, value2, value3)
    

    The reason for this is it insures that the column order is what you developed for as a SQL administrator can modify column order. It also allows you to insert a row with an identity Primary key with out specifying the value of the Primary Key Example

    CREATE TABLE [dbo].[foo](
        [fooid] [int] IDENTITY(1,1) NOT NULL,
        [name] [varchar](50) NULL,
     CONSTRAINT [PK_foo] PRIMARY KEY
    (
            [fooid] ASC
    )
    

    now my insert statement is simple

    Insert into foo (name)
    values
    ("John")
    

    the result in the table would be

    1, "John"
    
    0 讨论(0)
  • 2020-12-03 11:30

    if you have an identity column, you don't need to specify it in the insert statement.

    INSERT INTO qcRawMatTestCharacteristic  
    VALUES(1,1,1,1,1,1,1,'','','', GETDATE(), 1) 
    

    However, if you have a primary key that isn't an identity column, then you do need to specify it, because otherwise it'll try to insert a null and primary keys by default are non-nullable.

    0 讨论(0)
提交回复
热议问题