使用VBA Recordset将Excel工作表导出到SQL Server表

时间:2018-08-10 08:52:59

标签: sql-server excel vba ado

我正在尝试从Excel工作表中将98列〜200000行导出到SQL Server表。我正在跟踪来自此链接https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction

的代码

当我有较少的数据时,它工作正常,但是处理大数据需要时间。

我尝试了批量插入,将其插入到字符串形成方法中,但无法提高速度。使用VBA从excel导出到SQL服务器时,能否请您分享有关如何提高性能的想法

2 个答案:

答案 0 :(得分:0)

您可以创建XML,将其发送到SQL存储过程,然后在其中解码并插入。

它可以是超简单的XML-无需解析器。这是我正在使用的代码示例。但是不确定您说的“花费时间”是什么意思。我每天都用它来移动约5k行,并且要花几秒钟的时间-从未对其进行检查或针对速度进行过优化。

来自VBA的简单XML:

For i = 1 To RowsCount
    xml = xml & "<ROW><COLUMN1>" & Range("A1").Offset(i, 0).Value & "</COLUMN1><COLUMN2>" & Range("B1").Offset(i, 0).Value & "</COLUMN2></ROW>"
Next i

xml = "<DATA>" & xml & "</DATA>"

然后,将其发送到存储过程,进行解码并插入:

insert into MyTable
SELECT * FROM OPENXML(@handle, '/DATA/ROW', 2) WITH 
    ([COLUMN1] [nvarchar](12), [COLUMN2] [int])

答案 1 :(得分:0)

听起来您正在遍历所有记录,从本质上来说,该过程将很慢。而且,Excel相对较慢,特别是与SQL Server相比。也许您可以将作业转换为SQL,然后运行SQL作业。下面是一个示例脚本,该脚本使用Where子句。只需更改它即可满足您的需要(即,也许您不需要使用Where子句)。

Sub InsertInto()

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=DB_Name;Data Source=Server_Name"


'Create a new Command object
Set cmd = New adodb.Command

'Open the Connection to the database
cnn.Open

'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"

'Pass the SQL to the Command object
cmd.CommandText = strSQL


'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub