Import sql query on ODBC table in MS Access 2007 - sql

Using MS Access 2007 I would like to retrieve only part of an ODBC table.
I can import the whole table in Access but I don't need all of it and it would be a waste of space and performance to store the whole table when I only need certain columns.
In Excel I wrote a SQL query that let me retrieve only the part I'm interested in. What I'd like to know is: is it possible to import only the result of a SQL query in Access or do I have to retrieve the whole table and then run the query on it?
Is it possible using built-in Access module or should I turn to VBA?
Edit: Basically I would like to run the ODBC data connection below (currently used in Excel) in Access.
Connection string:
DSN=BLA1;
UID=BLA2;
DBQ=BLA3;
PWD=BLA4;
DBA=W;
APA=T;
EXC=F;
FEN=T;
QTO=T;
FRC=10;
FDL=10;
LOB=T;
RST=T;
GDE=F;
FRL=F;
BAM=IfAllSuccessful;
MTS=F;
MDI=F;
CSR=F;
FWC=F;
PFC=10;
TLO=0;
Command string:
SELECT *
FROM TEST TEST
WHERE (TEST.DATE_STAMP=?)
When I try to link the database I get the error The database engine can't find 'WTD.DATAPOINT_5/1000'. Make sure it is a valid parameter or alias name, that it doesn't include characters or punctuation, and that the name isn't too long. but when I use the Excel database connection I get no error and everything is updated.

You don't need to import the whole table. You could link to the ODBC table and then run a make-table query against that linked table to copy in only the rows and columns that you need.

Related

How to use a SQL Select statement with Power Query against an Access database?

I've got a query that joins 4 tables that I need to run against 4 different Access .mdb files (all have the same schema) so I can compare the results in Excel. Instead of creating 16 Power Queries and joining them into 4 queries (20 total query objects) I want to write a SQL statement that joins the tables and run it against each of the 4 different data sources. There's a chance that the SQL statement may need to be updated, so having it stored in one place will make future maintenance easier.
I could not find examples of this online and the way that Power Query writes M for an Access connection is based on one table at a time. I did not want a solution that used VBA.
Poking around with the various Power Query connectors I found that I can use the ODBC connector to connect to an Access database. I was able to adjust the parameters and pass it a standard SQL statement.
I put the SQL statement in a cell (C16 in the image) and named that range Package_SQL. I also have 4 cells where I put the path and filename of the 4 Access .mdb files I want to query. I name those ranges Database1 through Database4.
This is the configuration screen to set the database paths and set the SQL statement
let
// Get the Access database to work with.
dbPath = Excel.CurrentWorkbook(){[Name="Database1"]}[Content]{0}[Column1],
// Get the SQL statement from the named range
SQL = Excel.CurrentWorkbook(){[Name="Package_SQL"]}[Content]{0}[Column1],
Source = Odbc.Query("dbq=" & dbPath & "; defaultdir=C:\Temp;driverid=25;
fil=MS Access;maxbuffersize=2048;pagetimeout=5;dsn=MS Access Database", SQL),
#"Changed Type" = Table.TransformColumnTypes(Source,
{{"Issue_Date", type date}, {"Revision_Issue_Date", type date}})
in
#"Changed Type"
As you can see the magic is done in the following line. I didn't want the defaultdir to be hard coded to a folder that everyone may not have so I set it to C:\Temp. You may need to change it or even remove it and see if it makes a difference.
Source = Odbc.Query("dbq=" & dbPath & "; defaultdir=C:\Temp; driverid=25;
fil=MS Access;maxbuffersize=2048; pagetimeout=5; dsn=MS Access Database", SQL),
I made 4 instances of that query and created another query to combine the results. The query runs as fast as most any other Access query. I am very satisfied with this solution. The query can be altered and/or repurposed from the Excel sheet without digging through the Power Query scripts.
Note that this solution does not use any VBA.

Run query connected to another database in VBA Access

I am trying to run saved query inside VBA Access. That query is connected to another database and looks like that:
SELECT * FROM TABLE IN 'C:\USERS\Another_database.accdb'
This query is saved as "My_query" inside first Access database. VBA code looks like this:
Function My_function()
Set rst = CurrentDb.OpenRecordset("My_query", dbOpenDynaset)
End Function
When I try to run it i got an error:
Run-time error '3219'
Any ideas why? It works for normal queries (without IN 'C:\USERS\Another_database.accdb' part.
The most efficient way to get data from another Access database on an ongoing basis is with Linked Tables.
Click External Data on the ribbon, then New Data Source → From Database → Access
Browse to the source database, and make sure you choose Link to the data source by creating a linked table
Select one or more tables that you want to link
[
The linked tables will be created and you will be able to query the linked tables as if they were local to the current database.
More Information:
Office Support : Import or link to data in another Access database
Office Support: Manage Linked Tables
Maybe you need to define a Recordset first or try to remove the quotation marks you have in the example? The following example works fine:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("SELECT Field FROM Table IN 'here goes your path'")
Now you have an Array rs() in which you can loop.

Teradata Sql assistant not running SELECT statements

I am trying to run the follwoing sql queries in Teradata sql assistants :
DECLARE #myTablVar TABLE ( tablename varchar(100) )
INSERT INTO #myTablVar VALUES('?')
SELECT * from #myTablVar
Info:
I do not have permission to create tables. So I created the table variable.
I am using Teradata's Importa data feature to insert values into the table variable #myTablVar. There is only one column in the source file.
The system is configured someway such that sql server 2008 queries run only.
Issue:
When I run this, data are imported but the select statement is not
running, and so I can not see the result.
If I put semicoln after each statement then one error occurs :
"Only 1 statement is allowed for this type of import"
Any help?
SQL Assistant Import mode submits the entire query, as a single request, for each record in the Import file.
I'm not sure if SQL Server will like those 3 statements submitted multiple times.
If it is allowed, then the results of the Select statement will be written to a file - not returned to the application display.
Imports never return data to the display - they always write the results to a file whose name is composed of the Import file name plus '.log'. It will be located in the same directory as the Import file.
I don't know a lot about SQL Server 2008 but if it will keep the declared table between queries you could submit the Import first. Then submit the Select after it completes.
Note that prior to version 15.0 Import always submits the entire contents ofthe query window even if you have part of the query highlighted and you have the option set to submit only the highlighted part of a query. (That option did not apply to Import mode until version 15.)

SQL statement against Access 2010 DB not working with ODBC

I'm attempting to run a simple statement against an Access DB to find records.
Data validation in the records was horrible, and I cannot sanitize it. Meaning, it must be preserved as is.
I need to be able to search against a string with white space and hyphen characters removed. The following statement will work in Access 2010 direct:
select * from dummy where Replace(Replace([data1],' ',''),'-','') = 'ABCD1234';
Running it from an ODBC connection via PHP will not. It produces the following error:
SQL error: [Microsoft][ODBC Microsoft Access Driver] Undefined function 'Replace' in expression., SQL state 37000 in SQLExecDirect
Creating a query in the database that runs the function and attempting to search its values indirectly causes the same error:
select * from dummy_indirect where Expr1 = 'ABCD1234';
I've attempted to use both ODBC drivers present. ODBCJR32.dll (03/22/2010) and ACEODBC.dll (02/18/2007). To my knowledge these should be current as it was installed with the full Access 2010 and Access 2010 Database Engine.
Any ideas on how to work around this error and achieve the same effect are welcome. Please note, that I cannot alter the database in way, shape, or form. That indirect query was created in another mdb file that has the original tables linked from the original DB.
* Update *
OleDB did not really affect anything.
$dsn= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\dummy.mdb;";
I'm not attempting to use it as a web backend either. I'm not a sadomasochist.
There is a legacy system that I must support that does use Access as a backend. Data gets populated there from other old systems that I must integrate into more modern systems. Hence, the creation of an API with Apache/PHP that is running on the server supporting the legacy system.
I need to be able to search a table that has an alphanumeric case identifier to get a numeric identifier that is unique and tied to a generator (Autonumber in access). Users have been using it a trash box for years (inconsistent data entry with sporadic notations) so the only solution I have is to strip everything except alphanumeric out of both the field value and the search value and attempt to perform a LIKE comparison against it.
If not replace() which is access supported, what ODBC compatible functions exist that I can use do the same kind of comparison?
Just to recap, the Access db engine will not recognize the Replace() function unless your query is run from within an Access application session. Any attempt from outside Access will trigger that "Undefined function" error message. You can't avoid the error by switching from ODBC to OleDb as the connection method. And you also can't trick the engine into using Replace() by hiding it in separate query (in the same or another Access db) and using that query as the data source for your main query.
This behavior is determined by Access' sandbox mode. That linked page includes a list of functions which are available in the default sandbox mode. That page also describes how you can alter the sandbox mode. If you absolutely must have Replace() available for your query, perhaps the lowest setting (0) would allow it. However, I'm not recommending you do that. I've never done it myself, so don't know anything about the consequences.
As for alternatives for Replace(), it would help to know about the variability in the values you're searching. If the space or dash characters appear in only one or a few consistent positions, you could do a pattern match with a Like expression. For example, if the search field values consist of 4 letters, an optional space or dash, followed by 4 digits, a WHERE clause like this should work for the variations of "ABCD1234":
SELECT * FROM dummy
WHERE
data1 = 'ABCD1234'
OR data1 Like 'ABCD[- ]1234';
Another possibility is to compare against a list of values:
SELECT * FROM dummy
WHERE
data1 IN ('ABCD1234','ABCD 1234','ABCD-1234');
However if your search field values can include any number of spaces or dashes at any position within the string, that approach is no good. And I would look real hard for some way to make the query task easier:
You can't clean the stored values because you're prohibited from altering the original Access db in any way. Perhaps you could create a new Access db, import the data, and clean that instead.
Set up the original Access db as a linked server in SQL Server and build your query to take advantage of SQL Server features.
Surrender. :-( Pull in a larger data set to your PHP client code, and evaluate which rows to use vs. which to ignore.
I'm not sure you can do this with ODBC and your constraints. The MS Access driver is limited (by design; MS wants you to use SQL Server for back ends).
Can you use OLEDB? that might be an option.

Combining data from Excel with database

This is probably a simple question, but I really don't know what I'm doing in Excel, so hopefully someone can help me out.
I've been given an Excel spreadsheet that has two relevant columns to my task. The first column is an "External ID", and the second column is an "Internal ID". I need to select a bunch of data out of our databases (with various joins) using the Internal ID as the key, but then all of this data needs to be linked back to the External ID, and the only link between Internal/External is this spreadsheet.
For example, say a row of the spreadsheet looks like this:
ExtID IntID
AB1234 2
I need to select all the data relevant to the item with ID #2 in our database, but I have no way to get "AB1234" from the database, so I need to somehow relate this data back to "AB1234" using the spreadsheet.
What's the easiest way to accomplish this? The version of Excel is Excel 2007, and the database is Oracle, if that's relevant.
Note that I only have read permission to the production databases, so creating tables and importing the spreadsheet data to do a join is not an option.
Edited based on a comment
1 - Use MS Access to import the Excel sheet as a table.
2 - Link to your database table, also from within MS Access
External Data tab->other data sources->ODBC connection->choose yours->pick the table(s) you want
3 - Write an Access query to compare the values you want
Create->Query Design->Drop the tables you want, drag lines between them for relationships, click Run
Usually I use copy-paste and a good column-mode editor with macros to accomplish such tasks. It works fine if you only have a couple of Excel files.
Alot depends on how familiar you are with the tools you have available to you.
DO you have a tool you are familiar with that would make it easy to use the IntID to find those records? If so, can you do the query and paste the results back into the original spreadsheet in the column to the right of the column with the IntID?
If so, you will have what you want, a spreadsheet with the following columns:
ExtID (original)
IntID (original)
IntID (from Oracle)
Col1 (from Oracle)
Col2 (from Oracle) etc....
I'm not familiar with Oracle, but I know a lot of databases let you prepend a table name with # or something like that and create a temp table. Others have a temporary database where you can create things. Sometimes you can create a temp table even if you can't do anything else but select.
If you have access to do that, I would do the function as JosephStyons suggests (#2), insert your records into the temp table, and do a query based on that.
With Excel and VBA, you can use ActiveX Data Objects (ADO) as a high level way of using the OLE DB provider for a particular database. This lets you read the data from the database and you can then query that data and store the results in the spreadsheet.
Oracle OLE DB provider
ADO Guide