简体   繁体   中英

Exporting foreign key from many to many relationship to another table sql

I've a table

CREATE TABLE [dbo].[CoursesOfferedToBatches] (
    [CourseId] VARCHAR (50) NOT NULL,
    [Batch]    INT          NOT NULL,
    PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC),
    CONSTRAINT [FK_OfferedCourses_ToCourses] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Courses] ([Id]),
    CONSTRAINT [FK_CoursesOfferedToBatches_ToBatches] FOREIGN KEY ([Batch]) REFERENCES [dbo].[Batches] ([Id])
);

When I export CourseId as foreign key from above table into below table as shown below, it gives error shown below after table

CREATE TABLE [dbo].[StudentsRegisterToCoursesOffered]
(
    [StudentId] UNIQUEIDENTIFIER NOT NULL , 
    [CourseId] VARCHAR(50) NOT NULL, 
    PRIMARY KEY ([CourseId], [StudentId]), 
    CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [Students]([StudentId]), 
    CONSTRAINT [FK_StudentsRegisterToCoursesOffered_ToCoursesOffered] FOREIGN KEY ([CourseId]) REFERENCES [CoursesOfferedToBatches]([CourseId])
)

Error:

Update cannot proceed due to validation errors. Please correct the following errors and try again.

SQL71516 :: The referenced table '[dbo].[CoursesOfferedToBatches]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.

My question finishes here but for reference I'm adding all relevant tables:

CREATE TABLE [dbo].[Courses] (
    [Id]   VARCHAR (50)  NOT NULL,
    [Name] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


CREATE TABLE [dbo].[Students] (
    [StudentId]      UNIQUEIDENTIFIER NOT NULL,
    [DepartmentName] VARCHAR (50)     NOT NULL,
    [Address]        VARCHAR (250)    NULL,
    [TwitterLink]    VARCHAR (100)    NULL,
    [FacebookLink]   VARCHAR (100)    NULL,
    [MemberSince]    DATETIME         NULL,
    [ProfileViews]   BIGINT           DEFAULT ((0)) NULL,
    [CNIC]           CHAR (15)        NULL,
    [AboutMe]        VARCHAR (3000)   NULL,
    PRIMARY KEY CLUSTERED ([StudentId] ASC),
    CONSTRAINT [FK_Students_ToStudents] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Users] ([UserId]),
    CONSTRAINT [FK_Students_ToDepartments] FOREIGN KEY ([DepartmentName]) REFERENCES [dbo].[Departments] ([Name])
);


CREATE TABLE [dbo].[Batches] (
    [Id] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

The table CoursesOfferedToBatches needs to have its own primary key, which you have created as a compound key PRIMARY KEY CLUSTERED ([Batch] ASC, [CourseId] ASC) . It is this compound key that would be a foreign key in StudentsRegisterToCoursesOffered and not just the CourseId .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM