2009-04-17 60 views
1

我需要将数据从Excel电子表格导入到SQL Server中,但数据不是关系/规范化格式,因此导入向导不会削减它(我所知道的)。从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 

(我缺乏创造力的歉意拿出此时早晨“真实”数据......)

每一行包含一个独特的产品,但cateogry结构是重复的。我想这个数据导入到三个表:

Category 
SubCategory 
Product 

(我知道子类别应该被包含的范畴内,DB是不是我的设计)

我需要一种方法来导入基于类别唯一行然后是子类别列,然后在将其他列导入到产品时,根据名称获取对子类别的引用。

缺少脚本编写这个,有没有办法使用导入向导或其他工具来做到这一点?

回答

3

前段时间我有一个类似的问题,并没有找到任何简单的方法来使用导入向导来做到这一点。我解决导入问题的方式(因为这是一次性任务,而不是一直存在的问题)是从excel中创建一个简单的宏(VBA),它将简单地调用一个存储过程,使用每行作为参数。

存储的proc会智能地插入每个参数(列),然后获取该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宏有类似代码:原名DTS

 

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 

+0

我担心会发生这种情况,但谢谢你让我走向正确的方向。不幸的是,这不太可能是一次性的任务,我可能会略有不同的数据集来处理:( – roryf 2009-04-17 10:12:47

2

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

-1

其实一个好的软件要使用专门为这类工作的发展是关系Excel中 - 有一个试用版,但它可以在过去一段时间的试用期,它只是显示烦人的窗口,每使用一次。 www.relationalexcel.com

-1

该解决方案非常快的是在MS Access使用工具“分析表”,表格就会被Normalyze,试试吧!