Using SQL Like Statement in MS Access DoCmd.OpenForm - sql

Using MS Access, I am trying to search specific columns for strings. Using the WHERE argument of the DoCmd.OpenForm, I was able to get exact matches using "=". However, I need to use LIKE instead, since the end users will need to have a more liberal filter.
The problem is that I keep getting an error when I use % or * in the string making up the SQL:
stLinkCriteria = "[" & Combo_Filter_Name & "] Like %'" & Text_Filter_Name & "'%"
DoCmd.OpenForm stDocName, acFormDS, , stLinkCriteria
What am I doing wrong? The following code I was using before works perfectly, but again, I need to use LIKE:
stLinkCriteria = "[" & Combo_Filter_Name & "] = '" & Text_Filter_Name & "'"
DoCmd.OpenForm stDocName, acFormDS, , stLinkCriteria
Thanks

The problem here is that the % sign is outside the quotes.
You have written %'mysearch'%
You should write '%mysearch%'
(Where mysearch is the string you are searching for)
You may need to use * instead of % for MS Access though.

MS Access does not keep to the SQL standard, but uses * instead of % and ? instead of _ in like. See http://office.microsoft.com/en-us/access-help/like-operator-HP001032253.aspx

Related

Why does MS Access prompt to enter parameter in update query which already has values?

I am making a database where the user can change the name of a company in a table. However , whenever I use the update query, it asks for a parameter which is already supplied. The old company name is in the variable new_comp and then the new one is in the Me.comp1_box.Value.
Funny enough the query runs excellently whenever I hit ok and enter nothing inside the "Enter Parameter" setting
Dim record_changer As String
record_changer = "UPDATE " & "[" & new_comp & "]" & " SET " & "[" & new_comp & "]" & ".Company_Name =" & """" & Me.comp1_box.Value & """" & ";"
MsgBox (record_changer)
DoCmd.RunSQL (record_changer)
This is the final value of the record_changer.
UPDATE [EREDEON TECHNOLOGIES] SET [EREDEON TECHNOLOGIES].Company_Name="EREDEON TECH";
This is how it is when the code runs.
This is the query that it is supposed to run
It gives this prompt meaning it's supposed to run perfectly, meaning there is nothing wrong with the Query
This what pops up
Can anyone please help me out?
I am genuinely lost.The name of the Old Company name is EREDEON TECHNOLOGIES and the new name is EREDEON TECH
But funny enough when I just hit Okay without entering a value into the parameter dialogue box, it actually makes the changes.-_- weird
This happens, then I press "OK"
THEN THIS HAPPENS, Then I hit Okay
This is the table before.
It updates the table the new value which is EREDEON TECH. When I just hit OK, without typing anything into Parameter Dialogue.
Try changing your SQL string to the following. Note the single quotes change around Me.comp1_box.Value.
record_changer = "UPDATE " & "[" & new_comp & "]" & " SET " & "[" & new_comp & "]" & ".Company_Name ='" & Me.comp1_box.Value & "';"
Misused quote marks is the most common cause for the Parameter Value prompt. If that doesn't work, use this article to perform step-by-step trouble shooting on all of the other usual causes, Why does Access want me to enter a parameter value?
You can also reference the following articles:
MS Docs, Quotation marks in string expressions
Bytes, (') and (") - Where and When to use them
Fundamentally, the issue is due to the use of double quotes in VBA which works in Access SQL by itself but not via VBA using DoCmd.RunSQL. You could have used single quotes to enclose company name value.
However, avoid concatenating VBA literals to SQL queries with quotes in the first place. Instead, use the industry best practice of parameterization which is available in MS Access using QueryDefs in VBA and PARAMETERS clause in SQL:
Dim record_changer As String
Dim qdef As QueryDef
sql = "PARAMETERS new_name_param TEXT; " _
& "UPDATE [" & new_comp & "] " _
& "SET Company_Name = new_name_param;"
' SET UP QUERYDEF
Set qdef = CurrentDb.CreateQueryDef("", sql)
' BIND PARAMS
qdef!new_name_param = Me.comp1_box.Value
' RUN ACTION
qdef.Execute
' RELEASE RESOURCE
Set qdef = Nothing
Nonetheless, the need to concatenate table name, new_comp, in query is questionable database design. Proper names (EREDEON TECHNOLOGIES, GAME DISCOUNT STORE, SHOPRITE, etc.) should never be names of tables. Avoid maintaining a separate table for every company. Instead, normalize data for a single table of all companies, then run UPDATE with WHERE adding a second parameter.
' PREPARED STATEMENT, NO VARIABLE CONCATENATION
sql = "PARAMETERS new_name_param TEXT, old_name_param TEXT; " _
& " UPDATE Companies " _
& " SET Company_Name = new_name_param" _
& " WHERE Company_Name = old_name_param;"
Set qdef = CurrentDb.CreateQueryDef("", sql)
qdef!new_name_param = Me.comp1_box.Value
qdef!old_name_param = new_comp
qdef.Execute
In fact, since above SQL is now separated from VBA, save the query without VBA punctuation (&, ", or _) as a separate object and call it in QueryDefs by name:
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef!new_name_param = Me.comp1_box.Value
qdef!old_name_param = new_comp
qdef.Execute
Even better, if your parameters derive from controls on open forms, include them directly in query for a single line VBA call. Below runs the normalized version of single Companies table:
SQL (save as query object, adjust names to actuals)
UPDATE Companies
SET Company_Name = Forms!myForm!comp1_box
WHERE Company_Name = Forms!myForm!new_comp
VBA (no need to close action queries)
DoCmd.OpenQuery "mySavedQuery"

Problem with LIKE command on Visual Studio 2010 and Access, VB.NET

I have searched for answers but the ones I have found I can't get working.
I have a database written in MS Access located on a network drive. The front-end has been written in Visual Studio 2010 (VB). I can get the data OK but I need to do a LIKE search to see if there is any records that might match what the user has entered.
Essentially the database is a list of barcodes provided on media. Users provide a list of barcodes but this is done by eye and the last two letters / numbers can be missed, due to size, location or not provided. When scanning the barcode it reads the full details. For example 'AIF00511L6'.
If there is a duplicate then I need to inform the user that there might be one or more records. Duplicate barcodes are possible (don't ask), so I need to provide the details to the user so that they can make the final decision as to if this is the same or different media.
The code I have in VB is:
Dim SQLString as String = "SELECT COUNT(*) AS Count1 " &
"FROM " & Table & " " &
"WHERE " & Column & " " &
"LIKE '*" & Search & "*';"
The code at runtime SQLString is:
SELECT COUNT(*) AS Count1 FROM Assets WHERE aItem LIKE '*IF00511L*';
This works OK in Access (returns 1) but it's not working from VS. I have tried using the '%' in place of '*' but this is not working either. In VS it returns 0.
Any help on this would be appreciated.
I saved and restarted my project and made the below change and now it's working!
Dim SQLString As String = "SELECT COUNT(*) AS Count1 " &
"FROM " & Table & " " &
"WHERE " & Column & " " &
"LIKE '%" & Search & "%';"
So it needed to be a % and not *, something I tried and didn't work, Oh well.

Dsum function not working with Text field

I've tried just about everything i can think of on why i would get this error, but i have had no luck. I wrote a similar code that references that same table with numerical values that works fine, but when searching for text it has problems. The error code says the missing operator lies here: [ExpendetureStore] = 'Lowe's
TotalCostTextBox = DSum("[ExpendetureCost]", "ProjectExpendetures", "[ExpendetureStore] = '" & Me.StoreNameCombo & "'")
Lowe's has an apostrophe in its name. Access query engine is reading that apostrophe as a special character (text delimiter) in the compiled search string. If your data includes apostrophes, one way to deal with is to 'escape' the character - double it in the data with Replace() function. This forces Access to treat the character as normal text.
TotalCostTextBox = DSum("[ExpendetureCost]", "ProjectExpendetures", "[ExpendetureStore] = '" & Replace(Me.StoreNameCombo, "'", "''") & "'")
The same will happen with quote marks and are more challenging to deal with. Note the escaping of quote between quotes.
Replace("somevalue", """", """" & """")
Or may be easier to understand using Chr() function.
Replace("somevalue", Chr(34), Chr(34) & Chr(34))
Side note: Expendeture is a misspelling of Expenditure.

Again, variable in where clause

Using access 2010, windows 7, SQL Server
Can't get the hang of this. Have an SQL query that was generated in the qbe grid then put in VBA. The version that runs has a literal Transaction_Table.Account_Number and looks like:
"WHERE (((dbo_Transaction_Table.Sku)=""Transfer"")
AND ((dbo_Transaction_Table.Description) Like ""%TO%"")
AND ((dbo_Transaction_Table.Account_Number)=""655812""));"
But when I try to replace the literal with the contents of a text box :
"WHERE (((dbo_Transaction_Table.Description) Like ""%Transfer To%"")
AND ((dbo_Transaction_Table.Account_Number)=& Chr$(34) & Me.accntNo & Chr$(34)));"`
I get a syntax err (missing operator) in query expression
(((dbo_Transaction_table.Description) like "%Transfer To%")
And ((dbo_Transaction_Table.Account_Number)= & Chr$(34) & Me.accntNo & Chr$(34))))`
It sounds like you're just missing quotes between the constant string and the injected values
"WHERE (((dbo_Transaction_Table.Description) Like ""%Transfer To%"")
AND ((dbo_Transaction_Table.Account_Number)=" & Chr$(34) & Me.accntNo & Chr$(34) & "));"
Although you might look into using parameters instead. I'm not an expert on doing those from VBA but there should be plenty of examples out there.

escaping special character from string asp and ms access query

I have ASP code with MS Access and I am updating my records. While updating when I put special characters like single quotes(') in string it displays an error. When string is without special chars it works correctly.
Please help or give any solution. Here is my code.
<!--#INCLUDE FILE="ConnStr.asp"-->
dim fileTitle
dim fileDescription
dim fromDateX
dim toDateX
dim romTimeX
dim toTimeX
dim Location
dim LocationURL
dim FileID
fileTitle= request("fileTitle")
fileDescription= request("description")
fromDateX= request("fdate")
toDateX= request("tdate")
romTimeX= request("ftime")
toTimeX= request("ttime")
Location= request("location")
LocationURL= request("locationurl")
FileID= request("jID")
sql = "Update tblFileInfo Set sFDate='" & fromDateX & "',sTDate='" & toDateX & "', sFTime='" & romTimeX & "',sTTime='" & toTimeX & "',location='" & Location & "', locationURL='" & LocationURL & "', filetitle='" & fileTitle & "', description='" & fileDescription & "' Where ID=" & FileID
objConn.Execute(sql)
Response.Redirect("adminfiles.asp?msg=save")
As previous answer mentions, you should avoid updating or accessing your database in this way due to SQL injection.
If your script is just for a temporary database update and for personal use, the quick and dirty way is to escape the apostrophe by repeating it again with a Replace function.
sql = "Update tblFileInfo Set sFDate='" & Replace(fromDateX,"'","''") & "' ...."
OR replace with HTML equivalent.
sql = "Update tblFileInfo Set sFDate='" & Replace(fromDateX,"'","'") & "' ...."
Do not use this for anything but a quick one off scripts if you're strapped for time. Not recommended under any other circumstance.
Don't insert parameter values like this, be aware of SQL injections!
Use ADO Command with parameters or create a stored procedure that handles the insert/ updates. Both solutions will solve your problem with single quotes. A good example can be found here: http://www.xtremevbtalk.com/showthread.php?t=309329#post1337389