这是我的源表
Book | Employee | StartDate | EndDate
-------------------------------------
ABC PQR 02/02/2014 06/06/2014
QWE MNO 03/03/2014 07/07/2014
这是数据库架构,此数据应该适合...
Book
表
BookID | BookName
-----------------
1 ABC
2 QWE
Employee
表
EmployeeID | EmployeeName
-------------------------
1 PQR
2 MNO
BookEmployee
表
BookID | EmployeeID | StartDate | EndDate
------------------------------------------
1 1 02/02/2014 06/06/2014
2 2 03/03/2014 07/07/2014
注意:如果Book
和Employee
表中已存在Book
和Employee
,那么我们就不应该插入它们,而应使用ID
BookEmployee
表
答案 0 :(得分:1)
我只会做三个查询。
INSERT INTO [Book] (BookName)
SELECT DISTINCT Book
FROM [Source]
WHERE Book NOT IN (SELECT BookName FROM Book)
INSERT INTO [Employee] (EmployeeName)
SELECT DISTINCT Employee
FROM [Source]
WHERE Employee NOT IN (SELECT EmployeeName FROM Employee)
INSERT INTO [BookEmployee] (BookID, EmployeeID, StartDate, EndDate)
SELECT Book.ID, Employee.ID, Source.StartDate, Source.EndDate
FROM [Source]
INNER JOIN Book ON Book.BookName = Source.Book
INNER JOIN Employee ON Employee.EmployeeName = Source.Employee
如果你做了很多事情,你可以在交易中运行这些。您还可以添加一些MERGE
行为,但我不会烦恼,因为您没有要插入多于一列的内容。就最后的查询而言,合并行为也没有做任何事情,但我确信这会让你有足够的开始使其发挥作用。
但是,是的,你无法一次性完成所有这一切,""本身,即使你可以,这种方式比那种方式更具可读性。