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

后端 未结 8 601
野趣味
野趣味 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 keys in any relational database are not allowed to be NULL - it's one of the main, fundamental characteristics of a primary key.

    See: SQL by Design: how to Choose the primary key

    Never Null
    No primary key value can be null, nor can you do anything to render the primary key null. This is an inviolate rule of the relational model as supported by ANSI, of relational database management system (RDBMS) design, and of SQL Server.

    UPDATE: ok, so you want an "auto-increment" primary key in SQL Server.

    You need to define it as an INT IDENTITY in your CREATE TABLE statement:

     CREATE TABLE dbo.YourTable(ID INT IDENTITY, col1 INT, ..., colN INT)
    

    and then when you do an INSERT, you need to explicitly specify the columns to insert, but just don't specify the "ID" column in that list - then SQL Server will handle finding the proper value automagically:

     INSERT INTO dbo.YourTable(col1, col2, ..., colN) -- anything **except** `ID`      
     VALUES(va1l, val2, ..., valN)
    

    If you want to do this after having created the table already, you can do so in the SQL Server Management Studio's table designer:

    alt text

提交回复
热议问题