仅将新数据从Excel导出到SQL

时间:2010-04-02 13:05:19

标签: sql sql-server excel vba

以下Excel VBA代码将数据从电子表格导出到SQL:

Sub SQLIM()

          ' Send data to SQL Server
     ' This code loads data from an Excel  Worksheet to an SQL Server Table
     ' Data should start in column A and should be in the same order as the server table
     ' Autonumber fields should NOT be included'
     ' FOR THIS CODE TO WORK
     ' In  VBE you need to go Tools  References and check Microsoft Active X Data  Objects 2.x library


    Dim Cn As ADODB.Connection
    Dim ServerName As String
    Dim DatabaseName As String
    Dim TableName As String
    Dim UserID As String
    Dim Password As String
    Dim rs As ADODB.Recordset
    Dim RowCounter As Long
    Dim ColCounter As Integer
    Dim NoOfFields As Integer
    Dim StartRow As Long
    Dim EndRow As Long
    Dim shtSheetToWork As Worksheet
    Set shtSheetToWork = ActiveWorkbook.Worksheets("Sheet1")
    Set rs = New ADODB.Recordset


    ServerName = "WIN764X\sqlexpress" ' Enter your server name here
    DatabaseName = "two28it" ' Enter your  database name here
    TableName = "COS" ' Enter your Table name here
    UserID = "" ' Enter your user ID here
     ' (Leave ID and Password blank if using windows Authentification")
    Password = "" ' Enter your password here
    NoOfFields = 7 ' Enter number of fields to update (eg. columns in your worksheet)
    StartRow = 2 ' Enter row in sheet to start reading  records
    EndRow = shtSheetToWork.Cells(Rows.Count, 1).End(xlUp).Row ' Enter row of last record in sheet

     '  CHANGES
   ' Dim shtSheetToWork As Worksheet
   ' Set shtSheetToWork = ActiveWorkbook.Worksheets("Sheet1")
     '********

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & _
    ";Uid=" & UserID & ";Pwd=" & Password & ";"

    rs.Open TableName, Cn, adOpenKeyset, adLockOptimistic

    For RowCounter = StartRow To EndRow
        rs.AddNew
        For ColCounter = 1 To NoOfFields
            rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
        Next ColCounter
    Next RowCounter
    rs.UpdateBatch

     ' Tidy up
    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing

End Sub

我想将代码修改为:

  1. 检查SQL表中是否已存在来自A列的数据。
  2. 如果数据存在,则只更新而不是导入为新角色。
  3. 如果数据不存在,则将其作为新角色导入。

2 个答案:

答案 0 :(得分:0)

这是执行此任务的错误方法。请从SQL服务器执行此操作。如果您使用的是SQL Server 2008,请查找merge命令。

还考虑使用SSIS来完成此任务,这是比从VBA执行此操作更好的选择。或者在t-SQL中查找OPenrowset命令并按照这种方式执行。

答案 1 :(得分:0)

我建议将数据从Excel上传到SQL中的临时表,然后调用(也通过VBA)一个SQL存储过程,该过程包含适合您需要的逻辑,将来自登台表的数据合并到最终目标表中。 / p>