SQL Variable in Where Clause - sql

Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
I am trying to select the states for the selected city. There is a drop down box with a list of cities. That box is titled txtDestinationCity.
It says I have an error in my FROM clause.
Thank you

You miss a space and some quotes. How about:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE '" & Me.txtDestinationCity & "' = [TDestinationType].[tPreTravelDestinationCity]"
Copy that next to your original to see the difference.
And for reasons SQL, PLEASE reverse the comparison. Always mention the column left and the value right:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = '" & Me.txtDestinationCity & "'"
Since the quotes are annoying and easy to miss, i suggest defining a function like this:
Public Function q(ByVal s As String) As String
q = "'" & s & "'"
End Function
and then write the SQL string like that:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(Me.txtDestinationCity)
This makes sure you ALWAYS get both quotes at the right places and not get confused by double-single-double quote sequences.
If you care about SQL-injection (yes, look that up), please use the minimum
Public Function escapeSQL(sql As String) As String
escapeSQL = Replace(sql, "'", "''")
End Function
and use it in all places where you concatenate user-input to SQL-clauses, like this:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Lastly, breakt it for readability. I doubt your editor shows 200 characters wide:
Me.txtDestinationState.RowSource = _
"SELECT tPreTravelDestinationState " & _
"FROM [TDestinationType] " & _
"WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Note the trailing spaces in each line! Without them, the concatenation will not work.

It can be easier to troubleshoot your query construction if you set it to a variable (e.g., strSQL) first. Then you can put a breakpoint and see it right before it executes.

You need a space after WHERE. Change WHERE" to WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"

Related

Two combo values into sql string

I am trying to combine two combobox selected values in a sql string with the following code :
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings
WHERE plaasnaam = '" & CmbPlaasnaam.Text & "'" And aliasnaam = " '" &
CmbAliasnaam.Text & "'"
However, I think I am messing up with my quotes and double quotes. I get the following error message :
Additional information: Conversion from string "SELECT plaasnommer
FROM oesskatt" to type 'Boolean' is not valid.
You really ought to learn how to use the String.Format method or string interpolation. It is far less error-prone than using the concatenation operator (&) over and over. You can see the issue with your code simply by looking at the colour. Anything in a literal String should be red and you can see some of yours that should be red but isn't. Presumably it should be something like this:
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
Using String.Format would look like this:
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' And aliasnaam = '{1}'", CmbPlaasnaam.Text, CmbAliasnaam.Text)
As you can see, far less easy to mess up. String interpolation would look like this:
opdragplaasnommer.CommandText = $"SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{CmbPlaasnaam.Text}' And aliasnaam = '{CmbAliasnaam.Text}'"
Given that this is SQL code, an even better idea would be to use parameters. I'm not going to go into detail about that because there's information all over the place but it's something that you really need to learn. Apart from your code being less error-prone, it will help avoid crashes due to formatting issues and, most importantly, protect you from SQL injection attacks.
You have messed up with your string;
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
In VB .NET string concatination is performed with & symbol. And new line requires underscore.
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings" & _
" WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & _
CmbAliasnaam.Text & "'"
But I would suggest to use String.Format function in this case.
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' and aliasnaam = '{1}'",
CmbPlaasnaam.Text,CmbAliasnaam.Text)
And again this just another way. But, to say the truth, I hate concatination for SQL queries. Better to declare SQL Parameters and assign value to them.

Adding SQL to VBA in Access

I have the following SQL code:
SELECT GrantInformation.GrantRefNumber, GrantInformation.GrantTitle, GrantInformation.StatusGeneral, GrantSummary.Summary
FROM GrantInformation LEFT JOIN GrantSummary ON GrantInformation.GrantRefNumber = GrantSummary.GrantRefNumber
WHERE (((GrantInformation.LeadJointFunder) = "Global Challenges Research Fund")) Or (((GrantInformation.Call) = "AMR large collab"))
GROUP BY GrantInformation.GrantRefNumber, GrantInformation.GrantTitle, GrantInformation.StatusGeneral, GrantSummary.Summary
HAVING (((GrantSummary.Summary) Like ""*" & strsearch & "*"")) OR (((GrantSummary.Summary) Like ""*" & strsearch & "*""));
Which I want to insert into the following VBA:
Private Sub Command12_Click()
strsearch = Me.Text13.Value
Task =
Me.RecordSource = Task
End Sub
After 'Task ='.
However it keeps on returning a compile error, expects end of statement and half the SQL is in red. I have tried adding ' & _' to the end of each line but it still will not compile.
Any suggestions where I am going wrong? Many thanks
You have to put the SQL into a string...
Dim sql As String
sql = "SELECT blah FROM blah;"
Note that this means you have to insert all of the values and double up quotes:
sql = "SELECT blah "
sql = sql & " FROM blah "
sql = sql & " WHERE blah = ""some value"" "
sql = sql & " AND blah = """ & someVariable & """;"
After that, you have to do something with it. For SELECTs, open a recordset:
Dim rs AS DAO.Recordset
Set rs = CurrentDb.OpenRecordset(sql)
Or, for action queries, execute them:
CurrentDb.Execute sql, dbFailOnError
Without knowing how you plan to use it, we can't give much more info than that.
This conversion tool would be quite helpful for automating the process: http://allenbrowne.com/ser-71.html
I suggest to use single quotes inside your SQL string to not mess up the double quotes forming the string.
In my opinion it's a lot better readable than doubled double quotes.
Simplified:
Dim S As String
S = "SELECT foo FROM bar " & _
"WHERE foo = 'Global Challenges Research Fund' " & _
"HAVING (Summary Like '*" & strsearch & "*')"
Note the spaces at the end of each line.
Obligatory reading: How to debug dynamic SQL in VBA
Edit
To simplify handling user entry, I use
' Make a string safe to use in Sql: a'string --> 'a''string'
Public Function Sqlify(ByVal S As String) As String
S = Replace(S, "'", "''")
S = "'" & S & "'"
Sqlify = S
End Function
then it's
"HAVING (Summary Like " & Sqlify("*" & strsearch & "*") & ")"

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.

SQL Statement in Access

Ive been trying to get a query I ran in Access to run in VBA but I keep getting errors due to the number of exclamation marks I've been using. The statement I am using is
SQLstat = "SELECT tbl_Date_Check.DateofChecklist, tbl_Tasks.QuestionNumber,tbl_Tasks.Frequency, tbl_Tasks.Questions " _
& "FROM tbl_Tasks, tbl_Date_Check " _
& "WHERE (((tbl_Date_Check.DateofChecklist)=""" & [Forms]![Daily_Checker]![TxtDate] & """) And ((tbl_Tasks.Frequency) = """ & [Forms]![Daily_Checker]![ComFreq]"""))"
Any help would be great thanks
This can possibly be explained by the following SO question: What is the difference between single and double quotes in SQL?
This explains that you need to utilize single quotes '' to surround text in SQL in almost every instance. The fact that you are using double quotes "" may be what is causing the error.
I hope this helps.
-C§
It must read like this for dates:
SQLstat = "SELECT tbl_Date_Check.DateofChecklist, tbl_Tasks.QuestionNumber,tbl_Tasks.Frequency, tbl_Tasks.Questions " _
& "FROM tbl_Tasks, tbl_Date_Check " _
& "WHERE ((tbl_Date_Check.DateofChecklist = #" & Format([Forms]![Daily_Checker]![TxtDate], "yyyy\/mm\/dd") & "#) And (tbl_Tasks.Frequency = " & [Forms]![Daily_Checker]![ComFreq] & "))"

VBscript/SQL concatenation of %

Ok, I am new to the forum and fairly new to coding, I've searched high and low, and I understand that vbscript requires escapes or Chr() to use special characters. In the following code I need to concatenate a '%' after the "doc_no" as a wildcard for a sybase database to pull up the list of document numbers that I need to appear in my table.
I have tried
' " & doc_no " ' & Chr(37) " 'this returned that "&" is an invalid character
' " & doc_no " ' || Chr(37) "
' " & doc_no " ' + ""%"" " returned + as an invalid character
I have tried several variations of each type, and I cannot find any similar situation online. Any advice? Again, I am only 4 months into my programming life so bear with me please. Below is a snippet of the code from which the above originates.
<%
Dim document(1024)
counter = 0
cmdString = ""
cmdString = cmdString & "SELECT dbo.dsk_obj.obj_id,"
cmdString = cmdString & " docno = dbo.dsk_obj.obj_usr_num "
cmdString = cmdString & "FROM dbo.dsk_obj "
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "' I NEED TO CONCAT. % HERE "
objRS.Open cmdString, objConn, adOpenStatic, 3, adCmdText
WHILE (objRS.EOF = False)
document(counter) = objRS("docno")
counter = counter + 1
objRS.MoveNext
WEND
objRS.Close
%>
<% FOR ii = 0 TO counter -1 %>
<%=document(ii)%>
<%
NEXT
%>
the output should look something like this
1555307375-0001
1555307375-0002
1555307375-0003
Any help would be greatly appreciated! Thanks! Jeremy
First, you should avoid string concatenation because of SQL injection.
Now what you are trying to do is to create a SQL string in VBScript. The SQL you desire looks something like:
LIKE '123%'
To create this, you need a string in VBScript like:
Dim string = "LIKE '123%'"
To change out 123 for your doc number, you can do:
Dim string = "LIKE '" & doc_no & "123%'"
In your case, it would be:
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "%'"
But please don't do this. You should pass the parameter in instead of using string concatenation.