Importing more than 1000 rows from Excel to SQL-server

爷,独闯天下 提交于 2019-12-01 23:18:55

问题


The process is run in the environment of Excel VBA 2010 and MS SQL Server 2008.

Assume that there is a simple one column data with 1500 rows in an Excel-sheet and we want to export it to the database with SQL-queries in VBA code (SQL procedure in VBA exports maximum 1000 rows at once in default mode).

There is one limitation in this problem: the export procedure must be with dbclass-connection instead of ADODB connection. (The code-owner is not me. The code-owner is using dbclass for a quite big VBA code, so probably he wouldn't accept to change the whole code).

I found an option like lngRecsAff for ADODB.Connection which is used like:

Sub test() 
   Dim cn As ADODB.Connection 
   Dim strSQL As String 
   Dim lngRecsAff As Long 
   Set cn = New ADODB.Connection 
  cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls; Extended Properties=Excel 8.0" 

  strSQL = "Insert INTO [odbc;Driver={SQL Server};Server=SQL09;Database=Tom;UID=userID;PWD=password].tbl_test1 Select * FROM [Sheet1$]" 
  cn.Execute strSQL, lngRecsAff
  cn.Close 
  Set cn = Nothing 
End Sub

I tried to implement that lngRecsAff in my dbclass execution like:

Sub test()
  Dim connOk As Boolean
  Dim rs As New ADODB.Recordset
  Set dbclass = New clsDB
  Dim Value1() As Variant
  Dim lngRecsAff As Long
  Dim strSQL as String
  Dim mstrErr as Boolean

  dbclass.Database = "database_name"
  dbclass.ConnectionType = SqlServer
  dbclass.DataSource = "server_name"
  dbclass.UserID = Application.UserName

  connOk = dbclass.OpenConnection(False, True)
    If connOk = False Then
       MsgBox "Unsuccessful connection!"
    Else
       MsgBox "Successful connection"
    End If

  strSQL = "INSERT INTO [dbo].[table1](Column1) Values('" & Value1 & "')"
  mstrErr = dbclass.ExecuteSQL(strSQL, lngRecsAff) ' The result mstrErr is a Boolean 
   ' Some closing options here
End Sub

I got en error like lngRecsAff is not suitable for my ExecuteSQL procedure. Normally my execution mstrErr = dbclass.ExecuteSQL(strSQL) works without any problem.

Maybe I can do the SQL-procedure with a for-loop, then I can send the data in small pieces. But I want to find a more efficient, "nicer" solution which sends the whole array at once.

So is there any special option for dbclass which can send more than 1000 rows from Excel to the database?


回答1:


You can query the Excel-Sheet directly using liked server.

In your Management Studio click to "Server Objects" and then right click onto "linked server". There you'll be able to add a new linked server.

If you need further help you can find tuorials easily. One is here: https://www.mssqltips.com/sqlservertip/2018/using-a-sql-server-linked-server-to-query-excel-files/



来源:https://stackoverflow.com/questions/34204813/importing-more-than-1000-rows-from-excel-to-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!