I need to pull data from SQL server using a query where its statement is stored in a MS access table and dump the data into another table.
There are 2 tables, 01-MyStoredSQLs
and 02-tmpTableData
The problem is that there are 2 connections as well. That's why I called it Hybrid.
My Final result is the data from SQL Server into the tmpTableData
(result of a query where its statement is stored in the MyStoredSQLs table)
Public Sub DumpSQLServerData()
Dim conn As ADODB.Connection
On Error GoTo errMSG
Set conn = New ADODB.Connection
conn.ConnectionString = "DSN=myDSN; UID=MyID;Pwd=MyPWd"
conn.Open
Dim db As DAO.Database
Set db = CurrentDb
Dim rs As DAO.Recordset
'Retrieving the SQL Statment that is stored in the MyStoredSQLs table
Set rs = db.OpenRecordset("SELECT [Statement] FROM MyStoredSQLs WHERE ID=1")
Dim tmpSQL As String
Dim tmpINTOSQL As String
tmpSQL = rs(0)
'Hybrid statement
tmpINTOSQL = "INSERT INTO tmpTableData" & tmpSQL
conn.Execute (tmpINTOSQL), dbFailOnError
conn.Close
rs.Close
db.Close
Set conn = Nothing
Set rs = Nothing
Set db = Nothing
errMSG:
Debug.Print Err.Description
End Sub
You can't expect SQL server to magically be able to access tables stored elsewhere.
Execute the query in Access, and either use a linked table, or specify the location of the table, eg
INSERT INTO tmpTableData SELECT Something FROM [ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd].Schema.TableInSQLServer
If you want to execute the query on SQL server, not Microsoft Access, then SQL server will need to be able to access the Access database file, and use OPENROWSET
to query the Access table.
As an alternate, you can create a passthrough query, and use that to copy the table:
Dim qd As DAO.QueryDef
Set qd = db.CreateQueryDef("~tmpQuery")
qd.Connect = "ODBC;DSN=myDSN;UID=MyID;Pwd=MyPWd"
qd.ReturnsRecords = True
qd.SQL = tmpSQL
Set qd = Nothing
db.Execute "INSERT INTO tmpTable SELECT * FROM [~tmpQuery]"
db.QueryDefs.Delete "~tmpQuery"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.