Issue with SQL code in Microsoft Access - sql

I have a button in my database that is supposed to find a record when it is clicked. The issue I am encountering is that I want it to search for a record based on two fields.
This is my code:
I am using the SearchForRecord macro with Where Condition
="[Short Title] = " & "'" & [Combo101] & "'" And "[Baseline] = " & "'" & [Combo103] & "'"
It is not liking this. If I just have the Where condition as
="[Short Title] = " & "'" & [Combo101] & "'"
or I have it as
="[Baseline] = " & "'" & [Combo103] & "'"
then it works fine. But when I try to combine the two (which I need to do) it will not find any records.
I tried to break it up into two separate SearchForRecord macros and while that did return records when I clicked the button, it still wasn't working properly.
It would be ideal if someone could let me know why my original code was not working and what needs to be done to fix it.

Try:
="[Short Title] = '" & [Combo101] & "' AND [Baseline] = '" & [Combo103] & "'"

Related

Access DlookUp not working with multiple Criteria

The Dlookup Function is Giving me a syntax error I have tried multiple ways but none worked
x = DLookup("Clock_ID", "User_access", "Clock = " '" & Me.Clock_ID & _
& " AND Module = '" & Me.m_1 & "'")
I basically Need it to check 2 fields in the same table at the same time so the ID can be duplicated But the Module cant be duplicated.
I guess ID is numeric, so try:
x = DLookup("Clock_ID", "User_access", "Clock = " & Me.Clock_ID & " AND Module = '" & Me.m_1 & "'")

Ignore apostrophe in sql query from text box

I'm thoroughly enjoying my stay here at stack overflow, I have found more useful information than I can count.
However, through all of my searches, I have yet to find an answer to my issue.
I have a Winforms app that inputs data into an SQL database. I have an issue with the text box in this form posting to the database.
If a user inputs an apostrophe or a quotation mark the query in Visual studio stops at where that apostrophe is in the text box even if there is more data after that and does not enter the data into the database.
I know that putting a second apostrophe will cancel out the one that was input, however, I can't seem to read the data in the text box before the query executes to cancel them out. I have put an example of what works in this text box and what breaks the query in this question for further clarification.
I apologize, everyone, it seems I forgot to put my code into this post.
Dim InsertQuery As String = "INSERT INTO SelfInstallNotes (Troubleshooting, DateAndTime, [CL to OD], [Swapped Dscntd Clocks], [Upgrading to SaaS], [Update Version], [Created RPF], [Created RMA], [Clock Serial], [Case Number], [User], [Grabbed], [Account Manager], [Transferred to AM]) VALUES('" & Hidden.TextBox6.Text.ToString & "'" & "," & "'" & DateTimePicker1.Value & "'" & "," & "'" & CheckBox1.CheckState & "'" & "," & "'" & CheckBox2.CheckState & "'" & "," & "'" & CheckBox3.CheckState & "'" & "," & "'" & CheckBox4.CheckState & "'" & "," & "'" & CheckBox5.CheckState & "'" & "," & "'" & CheckBox6.CheckState & "'" & "," & "'" & TextBox2.Text & "'" & "," & "'" & TextBox1.Text & "'" & "," & "'" & TextBox6.Text & "'" & "," & "'" & Hidden.TextBox3.Text & "'" & "," & "'" & Hidden.TextBox4.Text & "'" & "," & "'" & Hidden.TextBox5.Text & "'" & ")"
But after reading all of you answers this code is most certainly WRONG and can cause issues later on down the road. I will try the answer posted below and update the thread accordingly.
This query will not post to DB due to the apostrophe in can't
while this input in the textbox will post without any issues, as there is no apostrophe or quotation marks.
The problem is worse than you know. This is also a huge security issue. Try putting the following text in your input:
'; DROP TABLE [MyCallTable];--
Or don't, if you value your data.
Fortunately, the solution is the same for both the security issue and for normal, everyday apostrophes; you quarantine all user input from the rest of the SQL command by using query parameters.
Here's an example:
var SQL = "SELECT * FROM Users WHERE LastName = #LastName";
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(SQL, cn))
{
//TextBox1 can have text with ' characters, and it won't matter.
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 25).Value = TextBox1.Text;
cn.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
}
There are other forms of this, too, depending on your environment, but the important thing is the text input is never at any time substituted directly in the SQL command — not even on the database server. This prevents any possibility of bad input injecting into the SQL. It also makes it easier to get things like date formats right, as now the ADO.Net provider will handle conversions for you.
The main thing to understand is if you ever find yourself doing anything like this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text + "'";
or even this:
sql = "SELECT * FROM [Table] WHERE Field='" + TextBox.Text.Replace("'", "''") + "'";
you're doing something very wrong.
This is one of those things that's important enough it's worth going back through an old code base to fix every instance where you've done it the wrong way before the next release, and it's not often I'll say that.
var stringvariable = tempString.Replace("'", "''");// this escapes the single quote

Access Form Dlookup - Using a Combo box for the expression value

Good Morning,
I am doing some work for a colleague and he wants a form creating where he can change to column that is looked at through a combo box as well as the criteria
I have tried the following
=DLookUp(" & [Combo8] & ","Product Guidelines","PC = '" & [Combo2] & "'")
but get an error, if i hard code the expression to one of the columns it works fine but when it's set to look at the combo box it doesn't work, I have tried several variants of the code but have no ran out of ideas
Please can someone help
Thank you
Look closely at your code. You are passing the literal string " & [Combo8] & " (including spaces and ampersands) as first parameter to DLookup.
Try
=DLookUp([Combo8], "Product Guidelines", "PC = '" & [Combo2] & "'")
or if the content of Combo8 has spaces,
=DLookUp("[" & [Combo8] & "]", "Product Guidelines", "PC = '" & [Combo2] & "'")
or maybe even with quotes around it:
=DLookUp("""[" & [Combo8] & "]""", "Product Guidelines", "PC = '" & [Combo2] & "'")
The syntax would be:
=DLookUp("[FieldNameToLookUp]","[Product Guidelines]","PC = '" & Me![Combo2] & "'")
as you probably don't have a field named Combo8.
If Combo8 holds that name, it would be:
=DLookUp("[" & Me!Combo8 & "]","[Product Guidelines]","PC = '" & Me![Combo2] & "'")

SQL syntax error on vba

I made a SQL statement in the add/update button in the query wizard I changed it back to SQL view to see how the program made me the code and when I copy and paste the same error on the If statement of the btnAdd it throws me a syntax error, but how?
here is the entire code:
Private Sub cmdAdd_Click()
'In the button add we have two options
'1. Insert
'2. Update
If Me.txtID.Tag & "" = "" Then
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"SELECT " & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "'"
Else
'Otherwise the data will be updated
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]));
End If
cmdClear_Click
tblClients_subform.Form.Requery
End Sub
it highlights me this row in red:
WHERE (([ClientID]=[Me].[txtID].[Tag]));
It appears that the following code is not on the same line
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]))
So you may want to change it to
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] " & _
"WHERE (([ClientID]=[Me].[txtID].[Tag]))"
In addition to Cableload's correct answer where the WHERE statement that was on a new code line was not connected to the previous line by the use of an underscore at the end of the first one, there is still a referncing issue.
You are referencing values in a UserForm like that were columns in a table so it is not finding the value you are looking for. To get the value into the SQL statement you need to come out of the literal string, reference the value, and then continue writing the string (not forgetting to enclose the value with '): -
CurrentDb.Execute "UPDATE tblClients SET " & _
"[ClientName] = '" & Me.txtName & "', " & _
"[Gender] = '" & Me.cboGender & "', " & _
"[City] = '" & Me.cboCity & "', " & _
"[Address (Fisical)] = '" & Me.txtAddress & "', " & _
"[Cellphone/Telephone] = '" & Me.txtCellphone & "' " & _
"WHERE [ClientID]=" & Me.txtID.Tag
I have spread it across multiple lines for ease of reading but obviously you can adjust your actual code however needed.
I would also question [ClientID]=" & Me.txtID.Tag, is the ClientID in the in the txtID.value or the txtID.Tag, they are different places. The value property is the value in the text box, the Tag property is more like a area for metadata that you can populate if needed but is not automatically populated by default.
Finally I'd like to refer you back to an answer to a previous question you had, at the bottom of the answer there was a tip about placing the resultant query into a Access Query in SQL view to get better information on the error, that would have helped you here too. To give further assistance on the 'resultant query'.
In debug mode before the while the CurrentDb.Execute is highlighted but before it is run (using F8 to step through each line until you get there, or placing a breakpoint on that line
Open the the Immediate Window if it is not already open (either Ctrl+G to from the menu bar 'View' > 'Immediate Window')
Copy all related code from the line after the CurrentDb.Execute statement, in this case it would be UPDATE ... .Tag
In the immediate window type a question mark and then paste in the rleated code and press enter
The immediate window will return the resultant string for you to try in a Query in SQL view.
Change the SELECT keyword to VALUES in your INSERT statement.
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"VALUES (" & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "')"
And the UPDATE should be this. The issue here was that you were trying to use Form controls in the SQL, but you needed to evaluate the controls first then concatenate their values to your literal string.
I'm wondering if you really need Me.txtID instead of Me.txtID.Tag
So sway that out if it doesn't work.
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = '" & me.txtName & "', tblClients.Gender = '" & me.cboGender & "', tblClients.City = '" & me.cboCity & "', tblClients.[Address (Fisical)] = '" & me.txtAddress & "', tblClients.[Cellphone/Telephone] = '" & me.txtCellphone & "' WHERE (([ClientID]=" & Me.txtID.Tag & "));"

Trouble using variables in VBA SQL WHERE Clause

I am trying to update a table using variables in VBA for Access. The statement is below.
DB.Execute "UPDATE tblSearchersList SET '" & vSearcherDay & "' = " & VHours & "
WHERE Member= '" & Me.cboMember.Column(1) & "'AND [Mission] = '" & Me.Mission & "'"
tblSearcherList is table to update
vSearcherDay is a variable that combines the letter "d" with a number, et(1,2,3,4,5) depending on other query
VHours is a decimal number (number of hours)
Member is a text value from Form Field Me.cboMember.Column(1)
Mission is a text value from form field Me.Mission
I get Runtime error 3061 - Too few parameters expected 2.
Hope I can get some help with this as I have been fighting it for awhile and am losing the battle.
Thanks
New code is this:
Sorry bout the comments thing. I am new and didn't quite know how to do this.
DB.Execute "UPDATE tblSearchersList SET " & vSearcherDay &_
" = " & VHours & " WHERE Member= '" & Me.cboMember.Column(1) & "' &_
" And [Mission] = '" & Me.Mission & "'"
I am quite embarrassed about this but I had the Member field name wrong. Should've been
MemberName instead. I really do appreciate all the quick help I got and will do better next time. It works perfectly. Thank you all.
Don't use apostrophes around field name. Instead
SET '" & vSearcherDay & "' = " &
do
SET " & vSearcherDay & " = " &