我创建了两个表,如下表所示,并根据表结构插入数据。
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,Level 16,State 1,Line 12 只有在使用列列表并且IDENTITY_INSERT为ON时,才能指定表'table1'中标识列的显式值。
有人可以回答我为什么会收到这些错误。
答案 0 :(得分:1)
将IDENTITY INSERT设置为ON
SET IDENTITY_INSERT table1 ON
为插入创建列列表,而不是直接插入而不指定列
INSERT INTO TABLE1(CUSTOMERNAME) SELECT 'john smith'
关闭身份插入
答案 1 :(得分:0)
您无需为customerID
传递table1
的值,因为其身份为ON
。它将自动递增。
首先插入table1
:
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')
然后让我们插入table2
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)
注意:您需要首先将记录插入table1
然后成功,然后只有您能够插入table2
只是因为您设置了{{1}引用Foreign Key
。
希望它可以帮到你!