Sql server 将DAT插入表时出错

Sql server 将DAT插入表时出错,sql-server,create-table,Sql Server,Create Table,我创建了如下两个表,并根据表结构插入了数据 create table table1( customerID int identity Primary key, customerName nvarchar(30)) create table table2( sensorID int identity Primary key, location nvarchar(20) not null, temp decimal not null, custID int foreign key(custID)

我创建了如下两个表,并根据表结构插入了数据

create table table1(
customerID int identity Primary key,
customerName nvarchar(30))

create table table2(
sensorID int identity Primary key,
location nvarchar(20) not null,
temp decimal not null,
custID int
foreign key(custID) references table1 (customerID))

Insert into table1 values(1000,'john smith')
Insert into table1 values(1001,'Mike Coles')
Insert into table1 values(1002,'sam carter')

Insert into table2 values(1000,'NY',70,1001)
Insert into table2 values(1001,'NY',70,1002)
Insert into table2 values(1002,'LA',60,1001)
Insert into table2 values(1003,'CA',67,1000)
Insert into table2 values(1004,'NY',70,1002)
但在执行时,我得到以下错误消息


Msg 8101,16级,状态1,第12行 只有在使用列列表且启用identity_INSERT时,才能为表“table1”中的identity列指定显式值


有人能回答我为什么会出现这些错误吗。

您不需要为
表1的
customerID
传递值,因为它的标识是
ON
。它将自动递增

首先插入
表1

SET IDENTITY_INSERT table1 OFF
Insert into table1(customerName) values('john smith')
Insert into table1(customerName) values('Mike Coles')
Insert into table1(customerName) values('sam carter')
然后让我们插入
表2

SET IDENTITY_INSERT table2 OFF
Insert into table2(location, temp, custID) values('NY',70,1)
Insert into table2(location, temp, custID) values('NY',70,2)
Insert into table2(location, temp, custID) values('LA',60,1)
Insert into table2(location, temp, custID) values('CA',67,1)
Insert into table2(location, temp, custID) values('NY',70,1)
注意:您需要首先将记录插入到
表1
中,然后成功打开,只有您设置了引用
表1的customerID的
外键才能插入到
表2

希望它能帮助你

  • 将标识插入设置为ON

    设置标识\u在

  • 为您的“插入式”创建列列表,而不是在不指定列的情况下直接插入

    INSERT INTO TABLE1(CUSTOMERNAME) SELECT 'john smith'
    
  • 关闭标识插入


  • 错误消息告诉您的确切内容。Msg 8101,级别16,状态1,第2行只有在使用列列表且启用identity_INSERT时,才能为表“table1”中的identity列指定显式值。Msg 8101,第16级,状态1,第3行只有在使用列列表且启用identity_INSERT时,才能为表“table1”中的标识列指定显式值。Msg 8101,第16级,状态1,第4行只有在使用列列表且启用identity_INSERT时,才能为表“table1”中的identity列指定显式值。我创建了另一个名为table11的表,执行并创建表11,使用上述数据进行显式插入,并设置IDENTITY\u INSERT table11 ON,然后设置IDENTITY\u INSERT table11 OFF。执行时收到相同的错误消息。我所做的是从表11的customerID中删除identity并插入上述值并执行。然后对表22执行相同的操作。EXECUTIFINSERT语句得到以下eror:Msg 213,级别16,状态1,第2行插入错误:提供的值的列名或数量与表定义不匹配。5此类错误…您正在使用哪个查询来查询
    表22
    ?我刚刚创建了另一个表22,它以前是我的表2,并按照您的建议将这些数据放入表2:插入表2值(1000,'NY',701001)插入表2值(1001,'NY',701002)插入表2值(1002,'LA',601001)插入表2值(1003,'CA',671000)插入到表2中的值(1004,'NY',701002)使用表1和表2数据库表架构,如您的问题所示,然后根据我更新的答案执行查询。请不要将值传递到标识列,因为我说它是自动递增的,并将值插入到该列中留给sql。