Import MS-SQL data into an Access Table ADO - sql-server

I hope that you can help me or point me in the right direction. For many years, I have used a very clean and simple method of importing data (within VB6, yes!) from a MS-SQL table into an MS-Access database/table as follows:-
WORKING QUERY WITH NO INNER JOINS
Dim myConnection As ADODB.connection
Dim mySQL As String
Set myConnection = New ADODB.connection
myConnection.Open "Driver={Microsoft Access Driver (*.mdb)};" & "Dbq=DB1.mdb;" & "DefaultDir=C:\Temp;" & "Uid=Admin;Pwd=;"
mySQL = "SELECT * INTO [Xray] FROM [ODBC;Driver=SQL Server; SERVER=myServer;DATABASE=myDatabase;UID=myUID;PWD=myPassword;].[ShipTo] WHERE [ShipTo].Company='ABC001'"
myConnection.Execute mySQL
Set myConnection = Nothing
However, for the first time, I now need to start working with Inner Joins. I thought that I could do something as simple as above, but I have come unstuck rather heavily and have no idea how to progress. My Inner Join query is below:-
SELECT
dbo.InvcHead.InvoiceNum AS DocNum,
SUM(dbo.InvcTax.TaxAmt) AS DocTaxAmt
FROM
dbo.InvcTax
INNER JOIN
dbo.InvcHead ON (dbo.InvcTax.InvoiceNum = dbo.InvcHead.InvoiceNum)
GROUP BY
dbo.InvcHead.InvoiceNum**
Because of my clear lack of experience using joins with my tried and tested method, I get an error which is probably because of my syntax, but I just cannot see the light. Below is the new connection string/query attempt:-
FAILED QUERY WITH INNER JOINS
Dim myConnection As ADODB.connection
Dim mySQL As String
Set myConnection = New ADODB.connection
myConnection.Open "Driver={Microsoft Access Driver (*.mdb)};" & "Dbq= DB1.mdb;" & "DefaultDir= C:\Temp;" & "Uid=Admin;Pwd=;"
mySQL = ""
mySQL = mySQL & "SELECT "
mySQL = mySQL & "dbo.InvcHead.InvoiceNum AS DocNum, "
mySQL = mySQL & "SUM(dbo.InvcTax.TaxAmt) As Doctaxamt "
mySQL = mySQL & "INTO [Xray] FROM [ODBC;Driver=SQL Server; SERVER= myServer;DATABASE= myDatabase;UID= myUID;PWD=myPassword;].[dbo.InvcTax] "
mySQL = mySQL & "Inner Join dbo.InvcHead ON (dbo.InvcTax.InvoiceNum = dbo.InvcHead.InvoiceNum)"
mySQL = mySQL & "Group By dbo.InvcHead.Invoicenum"
myConnection.Execute mySQL
Set myConnection = Nothing
The error message I get is "Syntax Error in Join Operation"
Is it possible to do this extraction using this method with an inner join query? I suspect my problem relates to the area of the script where I reference the first table of the join.
.[dbo.InvcTax] "
If this is not possible, is there a way to create a table dynamically (as I have done) but from a recordset instead?
Any help of a steer in the right direction will be massively appreciated.
Thanks,
Jack

The dbo prefix fails in Access SQL and you miss the database reference for the second table:
mySQL = ""
mySQL = mySQL & "SELECT "
mySQL = mySQL & "T1.InvoiceNum AS DocNum, "
mySQL = mySQL & "SUM(T1.TaxAmt) As Doctaxamt "
mySQL = mySQL & "INTO [Xray] FROM [ODBC;Driver=SQL Server;SERVER=myServer;DATABASE=myDatabase;UID=myUID;PWD=myPassword;].dbo.InvcTax AS T1 "
mySQL = mySQL & "INNER JOIN [ODBC;Driver=SQL Server;SERVER=myServer;DATABASE=myDatabase;UID=myUID;PWD=myPassword;].dbo.InvcHead AS T2 ON (T1.InvoiceNum = T2.InvoiceNum)"
mySQL = mySQL & "Group By T2.Invoicenum"

Related

JOIN an Access table and a SQL Server table in a single query from Excel VBA

I am using Excel 64-bit
I have a ms-access database and in this database I have normal ms-access table and some linked table from SQL Server, I have a query that is taking a reference of a linked table, and when I am firing that query from excel vba it is giving me an ODBC error, however I am successfully able to fetch non linked table from excel vba.
Now I am thinking about different approach, can it be possible to join ms-access and SQL Server table in a single query, I found some code from net and tried my luck, but it is not working and giving an error message "Could not find installable ISAM", below is the code that I am using.
Note:- table "PeopleMain" is a sql server table, and except this table all are ms-access table.
[code]
Sub FetchData3()
Dim rs As Object
Dim cn As Object
Dim ss As String
Dim conn As String
Dim accdb As Object
conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Workflow Tools (Michael Cantor)\Tool For Fixing Bug From Michael Cantor\PI MDT Reconciliation Workflow Tool\PI Database.accdb;Persist Security Info=False;Mode=Read"
ss = "SELECT RM.ReconciliationID, RM.FirmID, RM.FirmName, RM.DateRequested, RM.DueDate, Rm.ExtendedDueDate, " & _
"Requestor.Name, SecondaryRequestor.Name FROM " & _
"((ReconciliationMaster RM INNER JOIN Reconciliation_Fund RF ON RF.ReconciliationID = RM.ReconciliationID) " & _
"LEFT JOIN (SELECT Preferred_Name + ' ' + Last_Name AS Name, People_ID FROM " & _
"[Provider=sqloledb;Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain) Requestor " & _
"ON Requestor.People_ID = RM.PrimaryRequestor) LEFT JOIN (SELECT Preferred_Name + ' ' + Last_Name AS Name, " & _
"People_ID FROM [Provider=sqloledb;Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain) " & _
"SecondaryRequestor ON SecondaryRequestor.People_ID = RM.SecondaryRequestor WHERE RM.ReconciliationID = 522;"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open conn
rs.Open ss, cn
Sheet1.Cells.ClearContents
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
MsgBox "done"
End Sub
Thanks
Kashif
Access allows querying and joining in ODBC data sources, not OLEDB data sources.
Change the connection string used inside your query to an ODBC string:
[ODBC;Driver={SQL Server};Server=servername;Database=database;Trusted_Connection=Yes].PeopleMain
When available, I recommend using a more up-to-date ODBC driver, of course.

SQL: Input Prompt in an Access passthru query to SQL Server

I have a working query in Access to linked SQL Server tables that I pass user input to using
WHERE (RIGHT(dbo.qryrptWhereUsed.ITEM, 9)=[INPUT_PROMPT:])
I would like to continue using Access to store similar simple queries that require user input but want to do this via a passthru query directly to the SQL Server db thus eliminating the mirrored tables in Access.
How do I accomplish this?
You can use the following code:
Dim strPrompt As String
strPrompt = InputBox("Enter where used >")
With CurrentDb.QueryDefs("qryPass")
.SQL = "select * from dbo.qryWhereUsed where ITEM = '" & strPrompt & "'"
.Execute
End With
If you running a report, then just go:
Dim strPrompt As String
strPrompt = InputBox("Enter where used >")
With CurrentDb.QueryDefs("qryPass")
.SQL = "select * from dbo.qryWhereUsed where ITEM = '" & strPrompt & "'"
End With
DoCmd.OpenReport "myreport", acViewPreview

SQL query that uses a range in excel as the criteria

I use external data from an SQL query in excel to pull data onto a spreadsheet then the spreadsheet can be sent to one of my colleges in say the sales department and they can view the queried information.
I want to be able to have a cell that they can enter data into and press a refresh button.
So I need to do some thing like this:
SELECT Customer.CustomerCode, Customer.Name,
OrderHeader.OrderType, OrderHeader.OrderNumber
FROM Customer INNER JOIN
OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
WHERE (OrderHeader.OrderType = 2) AND (OrderHeader.OrderNumber = Range("A1").Value)
Not sure how or if this is possible and the reason I need to do this is because i'm going through lines from all the Quotes and if there is over 65536 then i'll have a problem.
This is what I have at the moment the SQL is different but that doesn't matter
The easiest way is to pull the values for the parameters into VBA, and then create the SQL statement as a string with the parameter values, and then populate the commandtext of the query.
Below is a basic example of the parameter in cell A1.
Sub RefreshQuery()
Dim OrderNo As String
Dim Sql As String
' Gets value from A1
OrderNo = Sheets("Sheet1").Range("A1").Value
'Creates SQL Statement
Sql = "SELECT Customer.CustomerCode, Customer.Name, " & _
"OrderHeader.OrderType , OrderHeader.OrderNumber " & _
"FROM Customer " & _
"INNER Join OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID " & _
"WHERE (OrderHeader.OrderType = 2) And (OrderHeader.OrderNumber = " & OrderNo & ") "
With ActiveWorkbook.Connections(1).ODBCConnection
.CommandText = Sql
.Refresh
End With
End Sub
This assumes you have the query in Excel to begin with, and that it's the only query. Otherwise you'll have to define the name of the query as below:
With ActiveWorkbook.Connections("SalesQuery").ODBCConnection
I hope that helps :)
Further to #OWSam's example using ODBC, we can also use ADO to pull back query results from SQL Server. Using ADO, you cannot use windows verification and you will need the user to input their password somehow, to be able to run the query.
Personally I create a userform which has UserName and Password. Username pre-populated using Environ, and then they can type their password into the relevant TextBox.
Sub sqlQuery()
Dim rsConn As ADODB.Connection, rsData As ADODB.Recordset
Dim strSQL As String, winUserName As String, pwd As String
winUserName = UCase(Environ("username"))
pwd = "mypassword" 'password needed here.
strSQL = "SELECT * FROM mydatabase" 'query
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider = sqloledb;" & _
"Data Source = [server name here];" & _
"Initial Catalog = [initial database];" & _
"Integrated Security=SSPI;" & _
"User ID = " & winUserName & ";" & _
"Password = " & pwd & ";"
.Open
End With
Set rsData = rsConn.Execute(strSQL)
Range("A1").CopyFromRecordset rsData
End Sub
Edit: You must go into references and turn on the Microsoft ActiveX Data Objects Recordset 6.0 library (or equivalent within your VBE).

Microsoft OLE DB Provider for SQL Server error '80040e14' Incorrect syntax near '='

I get this error when i try to retrieve the data from database using the following piece of code.
Can someone help?
set rs = Server.CreateObject("ADODB.recordset")
sql = " SELECT * from COMPANY WHERE COMPANY_ID = " & Request.Form("CompanyId")
rs.Open sql, cnn
First of all, this is bad practice to do ad-hoc queries without using parameters. SQL Injection attack info: http://en.wikipedia.org/wiki/SQL_injection
To answer the question, though, you need to have single quotes around your varchar or char value that you are searching for.
set rs = Server.CreateObject("ADODB.recordset")
sql = " SELECT * from COMPANY WHERE COMPANY_ID = '" & Request.Form("CompanyId") & "'"
rs.Open sql, cnn

Multi database query ACCESS and SQL SERVER

I'm not able to figure out how to make a multi database query usign two diffent ditabase.
The first database is an ACCESS mdb database and the second one is a SQL Server 2012 database.
I'm using Visual Basic 6.
The code I'm using is that:
ConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=C:\MyDatabase.mdb"
ConnectionString2 = "DSN=ODBC_NAME;UID=user;PWD=password"
SQL = "SELECT tabScheda.sWorkNum FROM tabScheda WHERE codScheda NOT IN" + _
" (SELECT ORDERID FROM [" + ConnectionString2 + "].V_PRESETTING_SP_HEADER WHERE MODE = 'TC')"
cn.Open ConnectionString1
Set rc = cn.Execute(SQL)
rc.Close
Set rc = Nothing
cn.Close
Set cn = Nothing
Please help me :D

Resources