SQL Server,无法在主键字段中插入null? [英] SQL Server, can't insert null into primary key field?

查看:1539
本文介绍了SQL Server,无法在主键字段中插入null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我准备好把这个头发撕开了。我是MS SQL的新手,而且还没有看到类似的帖子。



当我尝试这样做的一个语句:

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

我得到以下内容:


无法将值NULL插入
列'iRawMatTestCharacteristicId',

'Intranet.dbo.qcRawMatTestCharacteristic';
列不允许为空。 INSERT
失败。


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



任何想法!

解决方案

>任何关系数据库不允许为NULL - 它是主键的主要基本特征之一。



请参阅: SQL by Design:如何选择主键


从不空

无主键值null,也不能对
执行任何操作,使主键为null。 这是
由ANSI

关系数据库管理系统
(RDBMS)设计和SQL支持的关系型
模型的不可侵犯的规则服务器。


更新:好的,所以你想要一个自动递增主键在SQL Server



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

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

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

  INSERT INTO dbo.YourTable(col1,col2,...,colN) - 任何**除**`ID` 
VALUES(va1l,val2,...,valN)

如果你想这样做在创建表后,您可以在SQL Server Management Studio的表设计器中执行此操作:




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:

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

I get the following:

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

I understand the error, but the null value is for my my primary field with an int data type.

Any ideas!?

解决方案

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:

这篇关于SQL Server,无法在主键字段中插入null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆