Fastest way to transfer Excel table data to SQL 2008R2

后端 未结 6 744
囚心锁ツ
囚心锁ツ 2021-02-15 01:52

Does anyone know the fastest way to get data from and Excel table (VBA Array) to a table on SQL 2008 without using an external utility (i.e. bcp)? Keep in mind my datas

6条回答
  •  星月不相逢
    2021-02-15 02:29

    Having just tried a few methods, I came back to a relatively simple but speedy one. It's fast because it makes the SQL server do all the work, including an efficient execution plan.

    I just build a long string containing a script of INSERT statements.

        Public Sub Upload()
            Const Tbl As String = "YourTbl"
            Dim InsertQuery As String, xlRow As Long, xlCol As Integer
            Dim DBconnection As New ADODB.Connection
    
            DBconnection.Open "Provider=SQLOLEDB.1;Password=MyPassword" & _
                ";Persist Security Info=false;User ID=MyUserID" & _
                ";Initial Catalog=MyDB;Data Source=MyServer"
    
            InsertQuery = ""
            xlRow = 2
            While Cells(xlRow, 1) <> ""
                InsertQuery = InsertQuery & "INSERT INTO " & Tbl & " VALUES('"
    
                For xlCol = 1 To 6 'Must match the table structure
                    InsertQuery = InsertQuery & Replace(Cells(xlRow, xlCol), "'", "''") & "', '"  'Includes mitigation for apostrophes in the data
                Next xlCol
                InsertQuery = InsertQuery & Format(Now(), "M/D/YYYY") & "')" & vbCrLf 'The last column is a date stamp, either way, don't forget to close that parenthesis
                xlRow = xlRow + 1
            Wend
    
            DBconnection.Execute InsertQuery 'I'll leave any error trapping to you
            DBconnection.Close  'But do be tidy :-)
            Set DBconnection = Nothing
        End Sub
    

提交回复
热议问题