SQL Server存储过程,用于将数据从一个源插入/更新到多个目标表

时间:2014-07-29 19:28:38

标签: sql sql-server

这是我的源表

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

注意:如果BookEmployee表中已存在BookEmployee,那么我们就不应该插入它们,而应使用ID BookEmployee

1 个答案:

答案 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行为,但我不会烦恼,因为您没有要插入多于一列的内容。就最后的查询而言,合并行为也没有做任何事情,但我确信这会让你有足够的开始使其发挥作用。

但是,是的,你无法一次性完成所有这一切,""本身,即使你可以,这种方式比那种方式更具可读性。