【问题标题】:Exporting Excel sheet to SQL Server table using VBA Recordset使用 VBA 记录集将 Excel 工作表导出到 SQL Server 表
【发布时间】:2018-08-10 08:52:59
【问题描述】:
【问题讨论】:
标签:
sql-server
excel
vba
ado
【解决方案1】:
您可以创建一个 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])
【解决方案2】:
听起来您正在循环浏览所有记录,而且从本质上讲,这个过程会很慢。此外,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