INSERT语句与我的VB.net上的FOREIGN KEY约束冲突

时间:2015-09-15 04:27:48

标签: sql sql-server vb.net ado.net

所以我正在处理我的项目,然后我试图插入一些外键值

  

INSERT语句与FOREIGN KEY约束冲突   " SCHEDFK4&#34 ;.冲突发生在数据库" EnrollmentDatabase"中,   表" dbo.tblSubject",列' Subject_ID'。

以下是我的SQL实体

CREATE TABLE tblGradeLevel
(
     Grade_ID VARCHAR   (5) NOT NULL,
     Grade_Name VARCHAR (20)  NULL, 
     PRIMARY KEY (Grade_ID)
)

CREATE TABLE tblSubject
(
    Subject_ID VARCHAR (5)NOT NULL,
    Subject_Name VARCHAR (20) NOT NULL,
    Subject_Desc VARCHAR (20) NOT NULL,
    Grade_Name VARCHAR   (5) NOT NULL,
    PRIMARY KEY (Subject_ID), 
    CONSTRAINT SUBFK1 FOREIGN KEY (Grade_ID) 
        REFERENCES tblGradeLevel (Grade_ID)
)

CREATE TABLE tblSchedule
(
     Subject_Schedule_ID VARCHAR (5)NOT NULL,
     Section_ID VARCHAR (5)NOT NULL,
     Teacher_ID VARCHAR (5)NOT NULL,
     Time_In VARCHAR (20)NOT NULL, 
     Time_Out VARCHAR (20)NOT NULL, 
     Subject_ID VARCHAR (5)NOT NULL,
     Grade_ID VARCHAR (5)NOT NULL,

     PRIMARY KEY (Subject_Schedule_ID), 
     CONSTRAINT SCHEDFK1 FOREIGN KEY (Student_ID) 
         REFERENCES tblStudent_Information (Student_ID),
     CONSTRAINT SCHEDFK2 FOREIGN KEY (Section_ID) 
         REFERENCES tblSection (Section_ID),
     CONSTRAINT SCHEDFK3 FOREIGN KEY (Teacher_ID) 
         REFERENCES tblTeacher (Teacher_ID),
     CONSTRAINT SCHEDFK4 FOREIGN KEY (Subject_ID) 
         REFERENCES tblSubject (Subject_ID),
     CONSTRAINT SCHEDFK5 FOREIGN KEY (Grade_ID) 
         REFERENCES tblGradeLevel (Grade_ID)
 ) 

2 个答案:

答案 0 :(得分:0)

要避免发生此错误,请确保在该表中存在要插入引用另一个表的列的值。如果主表中不存在该值,则在对第二个表执行插入之前先插入该表。

为避免此错误,请先插入insert into the [dbo].[tblsubject]表,然后再插入[dbo].[tblSchedule]表。

答案 1 :(得分:0)

从您的错误中可以很容易地理解,您尝试在tblSchedule中插入记录,但Subject_ID表中缺少相应的tblsubject

您有两种方法可以解决此问题。

  1. 删除 外键约束
  2. tblsubject表中插入需要引用的tblSchedule条目。
  3. 您可以在MSDN链接here上阅读有关外键约束的更多信息。