我试图打开一个包含Select top 5 *表格的SQL存储过程,并将数据加载到名为Table3的Access表中。 如何设置Command Object ActiveConnection属性以使用当前的Access DB? 当我为它提供一个实际的连接字符串时,它表示用户已将其锁定。 此时,它会运行并打印输出结果,但不会插入值。它也没有给我一个错误。
'Use this code to run the SP and extract all the records
Public Sub ExecuteSPAsMethod2()
Dim rsData As ADODB.Recordset
Dim sConnectSQL As String 'to create connection to SQL Server
Dim sConnectAccess As String 'to create connection with Access DB (may not be neccessary)
Dim objCommand As ADODB.Command 'for INSERT results of SP into Access table
'Creating the connection string to SQL server
sConnectSQL = "Provider=SQLOLEDB;Data Source=MYSERVER; " & _
"Initial Catalog=SQLDatabase;Integrated Security=SSPI"
'Creating the Connection object and Recordset object
Set objConn = New ADODB.Connection
Set rsData = New ADODB.Recordset
'Opening the connection
objConn.Open sConnectSQL
'Execute the SP and give the results to the Recordset
objConn.SurveyDataSP "4", rsData
Do While Not rsData.EOF
Debug.Print rsData!Stratum
rsData.MoveNext
Loop
'Now write the data into Access Table
'Create connection string to Access DB table
'sConnectAccess = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Databse1.accdb;" & _
"Mode = Share Exclusive"
'Command object to be used for Access SQL query
Set objCommand = New ADODB.Command
'objCommand.ActiveConnection = sConnectAccess
'Insert new record in the DB
'Load the SQL string into the command object
Do While Not rsData.EOF
objCommand.CommandText = "INSERT INTO table3 (" & rsData!Stratum & ")"
objCommand.Execute
rsData.MoveNext
Loop
End Sub
答案 0 :(得分:0)
没有必要编写如此大量的代码并造成世界贫困。将执行命令保存为直通查询。
例如:
Exec 4
假设上面的名称是sp1,那么这段代码会将上面的所有数据附加到本地表中:
CurrentDb.Execute "INSERT INTO sp1Local select sp1.* from sp1"
因此,所有这些代码都可以使用一行VBA代码完成。