将Excel中的非规范化关系数据导入SQL Server [关闭]

问题描述 投票:1回答:4

我需要将数据从Excel电子表格导入SQL Server,但数据不是关系/规范化格式,因此导入向导不会削减它(据我所知)。

数据采用以下格式:

Category    SubCategory     Name        Description

Category#1  SubCategory#1   Product#1   Description#1
Category#1  SubCategory#1   Product#2   Description#2
Category#1  SubCategory#2   Product#3   Description#3
Category#1  SubCategory#2   Product#4   Description#4
Category#2  SubCategory#3   Product#5   Description#5

(道歉我在早上的这个时候缺乏创造'真实'数据的创造力......)

每行包含一个唯一的产品,但类别结构是重复的。我想将这些数据导入三个表:

Category
SubCategory
Product

(我知道SubCategory应该真的包含在Category中,DB不是我的设计)

我需要一种方法来导入基于Category和SubCategory列的唯一行,然后在将其他列导入Product时,根据名称获取对SubCategory的引用。

如果没有脚本编写,有没有办法使用导入向导或其他工具?

sql-server excel import etl
4个回答
3
投票

我刚才有类似的问题,并且没有找到使用导入向导执行此操作的简单方法。我解决导入的方式(因为这是一个一次性的任务,而不是一些可以解决的问题)是从excel创建一个简单的宏(VBA),它只是调用存储过程,使用每一行作为参数。

存储过程将智能地插入每个参数(列),然后获取ID以用作下一个参数插入的外键。

例如:


    DECLARE @CategoryID INT
    DECLARE @SubCategoryID INT

    -- Check that the Category exists
    IF NOT EXISTS (SELECT * FROM tblCategories WHERE CategoryName = @pCategoryName)
    BEGIN

        -- Your insert statement here, then grab the ID

        SET @CurrencyID = scope_identity()

    END
    ELSE
    BEGIN

        -- Set the category ID here

    END

VBA宏的代码类似于:


Private Sub CommandButton1_Click()

    Dim cnt As ADODB.Connection
    Dim wbBook As Workbook
    Dim wsSheet As Worksheet
    Dim intActiveRow As Long
    Dim intInsuranceProduct As Variant

    ' Get our connection
    Set cnt = CreateConnection()

    ' Read the input sheet
    Set wbBook = ActiveWorkbook
    Set wsSheet = wbBook.Worksheets(1)

    ' Ignore the header row
    intActiveRow = 2

    ' process every row into the database
     Do While (wsSheet.Cells(intActiveRow, 1)  "")

         ' execute the stored procedure, GenerateScript would create your SQL
         cnt.Execute (GenerateScript(wsSheet, intActiveRow))

         ' increment i for row count
         intActiveRow = intActiveRow + 1

     Loop

    End If

    'Cleaning up.

    cnt.Close
    Set cnt = Nothing
    Set wbBook = Nothing
    Set wsSheet = Nothing


End Sub


2
投票

您可能想要调查以前称为DTS(数据转换服务)的SSIS(SQL Server Integration Services)。 在SSIS中,可以使用Excel as a data source,您可以在其中指定数据的过滤器和转换,以便加载到相应的SQL Server表中。它可能需要一些研究,但它是一个非常强大的工具,并且还支持创建脚本任务的能力,如果你需要做一些不是开箱即用的事情。


-1
投票

实际上,专门为这类工作开发的一个好的软件是Relational Excel--有一个试用版,但它可以在试用期之后使用,它只是偶尔显示唠叨屏幕。 www.relationalexcel.com


-1
投票

解决方案非常快就是在MS Access中使用“分析表”工具,你的表将是Normalyze,试试吧!

© www.soinside.com 2019 - 2024. All rights reserved.