Use of Like * Works in MS-Access but Not VBA - sql

I have a simple query but am running into problems using LIKE in VBA. My SQL string in VBA is:
stsql1 = "Select Top 25 data.* from data where data.Description Like ('*') "
When I run this sql string in my VBA code I get no records returned, but if I copy/paste the same string into a query in SQL View in MS Access, the query returns the values I expect. Is there a trick to using the "Like" syntax in VBA?
I can provide additional code and a small version of the database if that would help.

For SQL, the database engine will accept either single or double quotes as text delimiters. So either of these 2 WHERE clauses will work.
WHERE some_field Like '*'
WHERE some_field Like "*"
VBA however only accepts double quotes as text delimiters, so you would have to use the second form.
Two other points about your SELECT statement:
Select Top 25 data.* from data where data.Description Like ('*')
TOP [number] is arbitrary without an ORDER BY clause
You don't need parentheses surrounding your Like pattern ... you can use Like "*"
If your VBA code is using ADO with that SELECT statement, you must change the wild card character from * to % ...
WHERE data.Description Like '%'

In ADO/VBA, you have to use % instead of * as the wildcard. I ran into this a couple times in the past ....

Realize that there are at least 2 (yes two!) LIKE operators here.
One is the LIKE operator of VBA.
The other is the LIKE operator of the SQL of the database you are attached to.
The usual wildcards in SQL are % (for any # of any characters) and _ (for one of any character).
Know also that MS Access can open databases that aren't Access; it could be Microsoft SQL Server, or Oracle or IBM DB2. (BTW, the database that is normal for Access is called Microsoft JET.) You may be sheltered from that truth when you create a Query object in Access - in that circumstance, you are using JET SQL even when it's a linked table you are querying.
However, under VBA, when using either DAO or ADO, you're talking directly to whatever the database system happens to be, in which case you MUST use the SQL of that specific system.
OK, short answer: Use % like cularis said.

I can't add a comment, but I think it would be worth noting that you have to use % even if you are querying MS Access.
(example: Outlook VBA runs query on an Access database. The proper query is select * where user like '%bob%', even though this query would not work if plugged directly into an MS Access query).

Related

Microsoft Query; use of SubString in Excel

I'm trying to filter results from a Query i have created in Microsoft Query to pull data from a database into my Excel sheet. Specifically I'm trying to filter out based on the nth character of a string.
I can easily filter out the based on the first char:
SOPOrderReturnLine.ItemCode Like 'A25%'
But I have no idea how I could filter to show only entries where the 10th char = "A". I'm sure I have to use a Substring function, but it's not familiar to me and I'm struggling to get it to work.
Try to edit your sql query and enter the following statement:
select * from SOPOrderReturnLine where substring(SOPOrderReturnLine.ItemCode,10,1) = 'A';
The statement should work for a MySql database as well as for an Sql Server in the background; (I've tested it with an MySql database).
Hope this helps.
In MSQuery (Jet under the covers, I think), the function is Mid.
SELECT * FROM tblLocation WHERE (Mid(LocationName,2,1)='e')
to find a lower case 'e' in the second location.
I assume when you say MS Query, you are running a query against a DBMS (SQL Server or some other via ODBC).
The use of substr, substring or mid should work, depending on which DBMS. That said, unless you're using MS Access, I think most DBMSs will support the underscore character as "any single character." It might even work in Access, but I don't know for sure. Therefore, I think in addition to the suggestions you've gotten, this will also work in most cases:
SOPOrderReturnLine.ItemCode Like '_________A%'
If you want to use substring, don't hold me to these, but I think:
Oracle / DB2 / SQLite - substr
Microsoft SQL Server / Sybase / MySQL - substring
MS Access - mid
PostgreSQL -substr or substring

SQL error using a wild card from a database

Basically trying to use a wildcard SQL to select and fields that hold the data from txtclass in the homework column of the database. But for some reason what i have done is causing an error. (im am using VB.net)
The standard wildcard character is the % not the *. It seems that you have taken this query directly from the designer of MS-Access (and perhaps the * is supported by this database system also from ADO.NET).
However there is a bigger problem
The wildcard should be part of the string to match against the LIKE not outside the single quotes
... LIKE '%" + txtclass.Text + "'))";
Said that you should start immediately to use a parameterized query instead of string concatenation if you want to avoid Sql Injection and parsing problems
Use like=* '%txtClass.text%' instead of like=' &txtClass.text&'
Try your SQL statement as:
SELECT tblQuiz.QuizID, tblQuiz.Classhomework FROM tblQuiz WHERE
tblQuiz.Classhomework LIKE '%' + pupilclass + '%';

Wildcards in MS Access SQL

I've written this SQL query in MS Access:
SELECT *
FROM Students
WHERE name like '_a*'
Which produces no results, even though I have names like danny and sara in the Students table.
THe '_' wildcard doesn't seem to work.
BTW,
like '*a*'
does return all names with a in them.
And ideas?
In Access query builder's dialect of sql, you need ? not _. If you connect to the same mdb backend via odbc you'll need to go back to using the standard wildcards.
See this page for details.

MS Access SQL DELETE - why would someone specify column names?

I'm having to support an Access .mdb file that someone else has written. One of the button functions in this .mdb calls out to delete some data in an external MSSQL database. All very straightforward, but this syntax isn't something I've seen before:
DELETE
tblEquipmentConnections.SourceEquip,
tblEquipmentConnections.EquipmentConnectionID
FROM tblEquipmentConnections
WHERE
tblEquipmentConnections.SourceEquip = [Forms]![frmEquipment]![EquipmentID];
Is that any different than this?
DELETE
FROM tblEquipmentConnections
WHERE
tblEquipmentConnections.SourceEquip = [Forms]![frmEquipment]![EquipmentID];
I can't find a case where specifying specific columns does anything - but I don't spend much time in Access, so I'm not sure how different the SQL syntax is...
Thanks!
Specifying the column names makes no difference. It's just an Access thing.
The reason they might be there is because Access used to generate DELETE statements that way (not sure if it still does).
The second form without columns names is obviously preferable.
I think the query has been built directly into Access query editor.
And generally we begin by building a select query. Then we change the query type from "Select query" to "Delete query". Then we display the query source by selecting "SQL Mode" where we copy / paste a sql statement like this one :
DELETE qc_Boxes.idBox, qc_Boxes.idScreen, qc_Boxes.title
FROM qc_Boxes;
This is absolutely redundant. The place between DELETE and FROM is used only when the deletion is performed based on a multi-table condition, but even in this case it contains table names and not field names. Also it can contain * which is also redundant. In MySQL, for example it's an incorrect syntax.

How do I deal with quotes ' in SQL [duplicate]

This question already has answers here:
How to anticipate and escape single quote ' in oracle
(2 answers)
Closed 7 years ago.
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
I (understandably) get an error.
How do I prevent this error from occurring. I am using Oracle and PLSQL.
The escape character is ', so you would need to replace the quote with two quotes.
For example,
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
becomes
SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'
That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.
Your SQL command would be :
SELECT * FROM PEOPLE WHERE SURNAME=?
Then, when you execute it, you pass in "O'Keefe" as a parameter.
Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).
I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See http://en.wikipedia.org/wiki/SQL_injection for a good starting point or the following classic xkcd comic.
Oracle 10 solution is
SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
Parameterized queries are your friend, as suggested by Matt.
Command = SELECT * FROM PEOPLE WHERE SURNAME=?
They will protect you from headaches involved with
Strings with quotes
Querying using dates
SQL Injection
Use of parameterized SQL has other benefits, it reduces CPU overhead (as well as other resources) in Oracle by reducing the amount of work Oracle requires in order to parse the statement. If you do not use parameters (we call them bind variables in Oracle) then "select * from foo where bar='cat'" and "select * from foo where bar='dog'" are treated as separate statements, where as "select * from foo where bar=:b1" is the same statement, meaning things like syntax, validity of objects that are referenced etc...do not need to be checked again. There are occasional problems that arise when using bind variables which usually manifests itself in not getting the most efficient SQL execution plan but there are workarounds for this and these problems really depend on the predicates you are using, indexing and data skew.
Input filtering is usually done on the language level rather than database layers.
php and .NET both have their respective libraries for escaping sql statements. Check your language, see waht's available.
If your data are trustable, then you can just do a string replace to add another ' infront of the ' to escape it. Usually that is enough if there isn't any risks that the input is malicious.
I suppose a good question is what language are you using?
In PHP you would do: SELECT * FROM PEOPLE WHERE SURNAME='mysql_escape_string(O'Keefe)'
But since you didn't specify the language I will suggest that you look into a escape string function mysql or otherwise in your language.
To deal quotes if you're using Zend Framework here is the code
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->quoteInto('your_query_here = ?','your_value_here');
for example ;
//SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' will become
SELECT * FROM PEOPLE WHERE SURNAME='\'O\'Keefe\''
Found in under 30s on Google...
Oracle SQL FAQ