SQL Server,无法在主键字段中插入null?

前端之家收集整理的这篇文章主要介绍了SQL Server,无法在主键字段中插入null?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我准备好把这个头发撕开了.我对MS sql很新,并且在任何地方都没有看到类似的帖子.

当我尝试这样做的声明:

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

我得到以下内容

Cannot insert the value NULL into
column ‘iRawMatTestCharacteristicId’,
table
‘Intranet.dbo.qcRawMatTestCharacteristic’;
column does not allow nulls. INSERT
fails.

我明白错误,但是null值是针对我的主字段和int数据类型的.

有任何想法吗!?

解决方法

任何关系数据库中的主键都不允许为空 – 它是主键的主要基本特征之一.

见: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.

更新:好的,所以你想要一个“自动递增”主键在sql Server中.

您需要在CREATE TABLE语句中将其定义为INT IDENTITY:

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

然后当您执行INSERT时,您需要显式指定要插入的列,但是不要在该列表中指定“ID”列,则sql Server将自动处理查找适当值:

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

如果要在创建表之后执行此操作,可以在sql Server Management Studio的表设计器中执行此操作:

原文链接:https://www.f2er.com/mssql/82599.html

猜你在找的MsSQL相关文章