插入关联表

时间:2016-05-05 05:15:21

标签: sql sql-server

我正在尝试在Visual Studio 2013上插入一个关联表,但我也相信我可能会错误地设置表的结构。我需要做的是关联表需要获取Tasks和Student表的主键。

预期结果:

StudentID   TaskID      Status
----------- ----------- ------
1           1           N
1           2           N
1           3           N
1           4           N
1           5           N
1           6           N
1           7           N
2           1           N
2           2           N
2           3           N
2           4           N
2           5           N
2           6           N
2           7           N

非常感谢任何帮助!

CREATE TABLE [dbo].[STUDENT] (
[StudentID]    INT            IDENTITY (1, 1) NOT NULL,
...
PRIMARY KEY CLUSTERED ([StudentID] ASC));


CREATE TABLE [dbo].[TASKS] (
[TaskID]       INT            NOT NULL,
[TaskName]     NVARCHAR (MAX) NULL,
[TaskCategory] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([TaskID] ASC));


CREATE TABLE [dbo].[ASSOCIATIVE] (
[StudentID] INT        NOT NULL,
[TaskID]    INT        NOT NULL,
[Status]    NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([TaskID] ASC, [StudentID] ASC),
CONSTRAINT [FK_ASSOCIATIVE_STUDENT] FOREIGN KEY ([StudentID]) REFERENCES [dbo].[STUDENT] ([StudentID]),
CONSTRAINT [FK_ASSOCIATIVE_TASKS] FOREIGN KEY ([TaskID]) REFERENCES [dbo].[TASKS] ([TaskID]));

1 个答案:

答案 0 :(得分:0)

你想要的是CROSS JOIN

INSERT INTO ASSOCIATIVE(StudentID, TaskID, Status)
SELECT
    s.StudentID, t.TaskID, 'N'
FROM STUDENT s
CROSS JOIN TASKS t

如果您想再次运行此操作并且想避免违反PK,请添加NOT EXISTS条件:

WHERE NOT EXISTS(
    SELECT 1 
    FROM ASSOCIATIVE a
    WHERE
        a.TaskID = t.TaskID
        AND a.StudentID = s.StudentID
)