简体   繁体   English

将数据从Excel导入到SQL Server中的主明细表

[英]Import data from Excel to Master detail tables in SQL Server

I have an excel sheet that has Four Columns 我有一个包含四列的Excel工作表

SaleID, SaleDate,PersonID, ProductID, SaleQuantity,UnitRate

I want to import this data in one to many relation table such that each person sale should be recorded saparately. 我想将此数据导入到一对多关系表中,以便每个人的销售都应被适当记录。 My tables are as follows 我的表如下

Sale Master
SaleID,SaleDate,PersonID

SaleDetail
SaleID,productID,SaleQuantity,UnitRate

I am trying to follow the instruction from here . 我正在尝试按照这里的指示进行操作。 I have tried the following query to get started 我尝试了以下查询以开始使用

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=d:\tmp.xlsx', 'Select * from [aa$]')

But it is giving me following error 但这给了我以下错误

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Office Access database engine could not find the object 'aa$'.  Make sure the object exists and that you spell its name and the path name correctly.".

Is there any other better way to do that 还有其他更好的方法可以做到这一点

在此处输入图片说明

Okay, I'm not sure if I did this as you wanted. 好的,我不确定我是否按照您的意愿进行了操作。 Since I saw that I could use SSIS, I used SSIS. 因为我看到可以使用SSIS,所以我使用了SSIS。 First I created a sample Excel file. 首先,我创建了一个示例Excel文件。 You said it has four columns but I see six columns: 您说它有四列,但我看到六列:

SaleID, SaleDate,PersonID, ProductID, SaleQuantity,UnitRate SaleID,SaleDate,PersonID,ProductID,SaleQuantity,UnitRate

And on my test DB I created two tables to import data to: 在测试数据库上,我创建了两个表以将数据导入到:

CREATE TABLE SalesMaster (
SalesID INT NOT NULL,
SalesDate DATE,
PersonID INT
    CONSTRAINT PK_SalesMaster_SalesID
        PRIMARY KEY (SalesID))


CREATE TABLE SalesDetail (
ProductID INT NOT NULL,
SalesQuantity INT,
UnitRate MONEY,
SalesID INT
    CONSTRAINT PK_SalesDetail_ProductID
        PRIMARY KEY (ProductID),
    CONSTRAINT FK_SalesDetail_SalesMaster_SalesID
        FOREIGN KEY (SalesID)
            REFERENCES SalesMaster(SalesID))

Then I created a SSIS package to the task. 然后,我为任务创建了一个SSIS包。 First on the Control Flow, I used two Data Flow tasks. 首先在控制流上,我使用了两个数据流任务。 The first one is for populating the SalesMaster table and the second one is for populating the SalesDetail table. 第一个用于填充SalesMaster表,第二个用于填充SalesDetail表。

Each data flow task will have the Excel Source adaptor and OLE DB Destination adaptor. 每个数据流任务都将具有Excel Source适配器和OLE DB Destination适配器。 When you configure the Excel source, make sure that you map the columns in the Excel file correctly. 配置Excel源时,请确保正确映射Excel文件中的列。 Then run the package and it should do the job. 然后运行该软件包,它应该可以完成工作。

Hope this was what you are looking for. 希望这就是您想要的。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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