创建三张表Student、Course、Enrollment
CREATE TABLE [dbo].[Student] (
[StudentID] INT IDENTITY (1, 1) NOT NULL,
[LastName] NVARCHAR (50) NULL,
[FirstName] NVARCHAR (50) NULL,
[EnrollmentDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([StudentID] ASC)
)
CREATE TABLE [dbo].[Course] (
[CourseID] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (50) NULL,
[Credits] INT NULL,
PRIMARY KEY CLUSTERED ([CourseID] ASC)
)
CREATE TABLE [dbo].[Enrollment] (
[EnrollmentID] INT IDENTITY (1, 1) NOT NULL,
[Grade] DECIMAL(3, 2) NULL,
[CourseID] INT NOT NULL,
[StudentID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([EnrollmentID] ASC),
CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID])
REFERENCES [dbo].[Course] ([CourseID]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID])
REFERENCES [dbo].[Student] ([StudentID]) ON DELETE CASCADE
)
不会覆盖或删除数据库已经存在的数据,将数据作为一张表更新到另一张表中。
merge into Course as Target
using (values
(1,'Economics',3),
(2,'Literrature',3),
(3,'Chemistry',4)
)
as Source (CourseID,Title,Credits)
on Target.CourseID =Source.CourseID
when not matched by target then
Insert(Title,Credits)
values(Title,Credits);
merge into Student as Target
using(values
(1,'Tibbetts','Donnie','2013-09-01'),
(2,'Guzman','Liza','2012-01-13'),
(3,'Catlett','Phil','2011-09-03')
)
as Source (StudentID,LastName,FirstName,EnrollmentDate)
on Target.StudentID=Source.StudentID
when not matched by Target then
Insert (LastName,FirstName,EnrollmentDate)
values (LastName,FirstName,EnrollmetnDate);
Merge into Enrollment as Target
using (values
(1,2.00,1,1),
(2,3.50,2,2),
(3,4.00,2,3),
(4,1.80,2,1),
(5,3.20,3,1),
(6,4.00,3,2)
)
as Source (EnrollmentID,Grade,CourseID,StudentID)
on Target.EnrollmentID =Source.EnrollmentID
when not matched by Target then
Insert (Grade,CourseID,StudentID)
values (Grade,CourseID,StudentID);