create table STAFF
(
StaffID TINYINT IDENTITY NOT NULL,
StaffName varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk
foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk
foreign key (Mentor) references staff(StaffID)
);
表已成功创建。但是当我要插入这样的值时:
insert into STAFF
values ('Adeesha', '077282018', 'M', '1997-11-30', '', '5'),
('Kavitha', '0772556899', 'F', '1956-11-28', '', '4'),
('Patee Aiya', '0775669844', 'M', '1954-01-04', '', '3'),
('Chanuka', '0772562984', 'M', '1997-02-24', '', '2'),
('Umesha', '0723328284', 'F', '1997-11-26', '', '3');
我收到以下错误:
Msg 547,Level 16,State 0,Line 1
INSERT语句与FOREIGN KEY SAME TABLE约束“mentor_fk”冲突 冲突发生在数据库“F_T”,表“dbo.STAFF”,列'StaffID'。
答案 0 :(得分:3)
空字符串(''
)与NULL
不同。您应该使用NULL
:
insert into STAFF(StaffName, Phone, Gender, DoB, Mentor, Payment_ID)
values ('Adeesha', '077282018', 'M', '1997-11-30', NULL, 5),
('Kavitha', '0772556899', 'F', '1956-11-28', NULL, 4),
('Patee Aiya', '0775669844', 'M', '1954-01-04', NULL, 3),
('Chanuka', '0772562984', 'M', '1997-02-24', NULL, 2),
('Umesha', '0723328284', 'F', '1997-11-26', NULL, 3);
注意:
insert
时,列出要插入表中的所有列。这是一种最佳做法。identity
列。它会自动生成。NULL
表示NULL
而不是空字符串。它们不一样。