Select with 2 conditions - mysql

can you please help me to fix the following code:
The code is trying to get data according to the 2 conditions:
Select data when a checkbox and a value form a drop down list is checked
Select data when only a checkbox is checked ( this one is working fine so I am not going to list it)
If I select multiple check boxes the values are shown properly but when I try to add the second condition no values are shown.
Date looks like this DD/MM/YY
I am using vb and mysql(DB)
If c1check AndAlso ComboBox2.SelectedItem > 0 Then
searchQuery = "Select USERS_NUMBER FROM DB WHERE EXPIRATION_DATE LIKE '%" _
& String.Join("%'and EXPIRATION_DATE LIKE " + "'%", myList) _
& + "%' AND RIGHT(EXPIRATION_DATE, 3) = '%" & Trim(ComboBox2.SelectedItem.ToString) & "'"

Related

Is it posible to have 2 Select statements with 2 different outputs in 1 query?

So I'm using MS Access to have users access a mysql database. I don't use linked tables rather connect to the database using ODBC DAO connections.
I'm generating a report which at the bottom gives the balance of the account. So far in my query I have been able to get all the data I need from the database except for the balance. Reason is that all the data I pull from database is filtered by a where statement between two dates and a company id. For the balance however I need another set of results giving me the sum of a whole column.
Reason I need to put this on a single sql query is because I will then pass this query to the recordsource of the report thus I cant use two queries.
I tried to use UNION but it doesnt work since I'm using a continuous form to show all results it creates more rows to fit for the second select statement.
This works as intended.
SELECT tbl10prepago.NumeroFactura, tbl10prepago.Fecha, tbl12vehiculosprepago.Tablilla, tbl11empleadosprepago.NombreEmpleado, tbl10prepago.Litros, tbl10prepago.CostoLitro, tbl10prepago.CantidadDinero, tbl13companiasprepago.NombreCompania, tbl13companiasprepago.Concepto, tbl5localidades.NombreLocalidad, tbl5localidades.DireccionPostal, tbl5localidades.Telefono
FROM (tbl10prepago INNER JOIN tbl12vehiculosprepago ON tbl10prepago.IdVehiculo = tbl12vehiculosprepago.ID)
INNER JOIN tbl11empleadosprepago ON tbl10prepago.IdEmpleado = tbl11empleadosprepago.ID
INNER JOIN tbl13companiasprepago ON tbl10prepago.CompaniaID = tbl13companiasprepago.ID
INNER JOIN tbl5localidades ON tbl13companiasprepago.LocalidadServicio = tbl5localidades.ID
WHERE tbl10prepago.Fecha BETWEEN '" & Format(Me.Text40, "yyyy-MM-dd HH:mm:ss") & "' AND '" & Format(Me.Text42, "yyyy-MM-dd HH:mm:ss") & "'
AND tbl10prepago.CompaniaID = " & Me.Combo34.Column(0) & "
ORDER BY tbl10prepago.Fecha;
What I need to add is this:
SELECT SUM(tbl14pagoprepago.pago) as [BALANCE]
FROM tbl14pagoprepago
WHERE tbl14pagoprepago.IDCompania = " & Me.Combo34.Column(0) & "
And not add it to the first Select results or filter by date also.
Thank you all in advance!
union will only work if you have same number of columns. What I can think of is you can add this balance field as new column.
SELECT tbl10prepago.NumeroFactura, tbl10prepago.Fecha, tbl12vehiculosprepago.Tablilla, tbl11empleadosprepago.NombreEmpleado, tbl10prepago.Litros, tbl10prepago.CostoLitro, tbl10prepago.CantidadDinero, tbl13companiasprepago.NombreCompania, tbl13companiasprepago.Concepto, tbl5localidades.NombreLocalidad, tbl5localidades.DireccionPostal, tbl5localidades.Telefono,
(SELECT SUM(tbl14pagoprepago.pago) FROM tbl14pagoprepago
WHERE tbl14pagoprepago.IDCompania = " & Me.Combo34.Column(0) & ") as [Balance]
FROM (tbl10prepago INNER JOIN tbl12vehiculosprepago ON tbl10prepago.IdVehiculo = tbl12vehiculosprepago.ID)
INNER JOIN tbl11empleadosprepago ON tbl10prepago.IdEmpleado = tbl11empleadosprepago.ID
INNER JOIN tbl13companiasprepago ON tbl10prepago.CompaniaID = tbl13companiasprepago.ID
INNER JOIN tbl5localidades ON tbl13companiasprepago.LocalidadServicio = tbl5localidades.ID
WHERE tbl10prepago.Fecha BETWEEN '" & Format(Me.Text40, "yyyy-MM-dd HH:mm:ss") & "' AND '" & Format(Me.Text42, "yyyy-MM-dd HH:mm:ss") & "'
AND tbl10prepago.CompaniaID = " & Me.Combo34.Column(0) & "
ORDER BY tbl10prepago.Fecha;

How do I get the value of a Form into an SQL query?

I am trying to get an Access SQL query that does this (semi-pseudocode below)
UPDATE SignIn SET SignIn.Complete=True, CompletedBy=(Select [FirstName] & " " & [LastName] AS EmployeeName From UserList where POid = Forms!HiddenUserCheck!txtPOid), CompletedDateTime=Now()
So after the query would run, the data in the database would look like
Complete EmployeeName CompletedDateTime
True John Smith 3/23/2017 8:34:10 AM
THe update query doesn't work because of syntax and not sure how to fix it.
The exact error message is
Invalid Memo, OLE, or HyperLink Object in subquery '[FirstName] & " "
& [LastName]'.
The query could be throwing a fit because of the Double Exclamation marks. Instead of
Forms!HiddenUserCheck!txtPOid
Try
Forms!HiddenUserCheck.txtPOid
You also have an extra ) at the end of your WHERE Statment
OK, then your issue may be that the subquery may return more than one record:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First([FirstName] & " " & [LastName]) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
If your name fields are Memo/LongText fields, that may be the source of the error. If so, try:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First(Left([FirstName], 255) & " " & Left([LastName], 255)) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
Edit.
You may try using DLookup for the subquery:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
DLookup("[FirstName] & " " & [LastName]", "UserList", "POid = " & Forms!HiddenUserCheck!txtPOid & ""),
CompletedDateTime = Now()

Multi-field searches in Access with blank fields

I have a table in access (simplified) with fields of sex, first name, last name, and phone number.
Sex First Last Phone
F Alice Smith
M Bob 111-111-1111
F Smithe 111-111-1112
M Charlie Smith
F Eve Drop 111-111-1113
I have created a form along with a query to search for the records, using the criteria of
Is Null Or Like "*" & [Forms]![Search]![Criteria] & "*"
where Search is the name of my form, and Criteria is the name of the individual entries on my form.
Right now, if I search for Sex F and the last name Smith, and leave the first and last name fields blank, I want to be able to see the records for "Alice Smith" and "Smithe". But instead, I only get the record of "Alice Smith". Furthermore, if I search for Sex F and phone number 111, I get results for Alice, Smithe, and Eve. Similarly, if I just search for phone number alone, I will get all five records.
I'm assuming that I'm doing something wrong here, but I can't tell what it is. Based on the conditional logic of or, the results should be either Null or 111 (and similar for the other fields), so I guess it is behaving as expected. I've tried xor however, and I get the same result (and even if it does work the way I'm thinking it would, it would seem bad since a blank entry would be interpreted as null instead of "search every entry". I've tried using iif, which should be the correct way to do this, but it appears to not work when placed in the criteria field. Am I missing something here?
Null is the special value (with the meaning not-known) and it is NOT the same as a blank text field, which has the value "" (empty string).
So adjust your criteria to accept the value "".
For multi-field search use criteria for each field like this:
WHERE
([Sex] Like "*" & [Forms]![Search]![CriteriaSex] & "*"
OR Nz([Forms]![Search]![CriteriaSex],"")="")
AND ([First] Like "*" & [Forms]![Search]![CriteriaFirst] & "*"
OR Nz([Forms]![Search]![CriteriaLast],"")="")
AND ([Last] Like "*" & [Forms]![Search]![CriteriaLast] & "*"
OR Nz([Forms]![Search]![CriteriaLast],"")="")
AND ([Phone] Like "*" & [Forms]![Search]![CriteriaPhone] & "*"
OR Nz([Forms]![Search]![CriteriaPhone],"")="")
In this case every condition will be TRUE if corresponding criteria field is empty.
Another way to build this query would be to build a string based upon which fields are populated.
q = "SELECT * FROM table "
w = ""
IF(nz([Forms]![Search]![Criteria1],"")<> "") THEN
w = "WHERE [table]![field] like '*" & [Forms]![Search]![Criteria1] & "*'"
END IF
IF(nz([Forms]![Search]![Criteria2],"")<> "") THEN
IF (w="") THEN
w=" WHERE "
ELSE
w=w & " AND "
END
w = w & " [table]![field] like '*" & [Forms]![Search]![Criteria2] & "*'"
END IF
IF(nz([Forms]![Search]![Criteria3],"")<> "") THEN
IF (w="") THEN
w=" WHERE "
ELSE
w=w & " AND "
END
w = w & " [table]![field] like '*" & [Forms]![Search]![Criteria3] & "*'"
END IF
q = q & w

"Data type mismatch in criteria expression"

I have tried to select all records from a table from date1 to date2, Example Jun 28, 2014 to Jan 05, 2015, for display. Basically, sort out selected records based on date criteria. Big thanks if anyone could point out my mistake.
What I tried to do here is allowed user to select specific dates from calendar to view the records
I have gone through all answers, but still couldn't find similar solution to mine. I think, there may be some error in my syntax.
sqlDateRangeSearch = "Select * from BatteryDataTable where ((BatteryDateChanged) <= ""*" & Me.FromDTPicker.Value & "*"")" & " and ((BatteryDateChanged) <= " & """*" & Me.ToDTPicker.Value & "*""));"
Me.RecordSource = sqlDateRangeSearch
I noticed you have wildcard characters in the search criteria for the query. If using dates, you'll want to avoid those. Also, you don't need quotes for dates in access queries. If you're dynamically creating SQL I'd use something like:
sqlDateRangeSearch = "Select * from BatteryDataTable where (BatteryDateChanged <= #" & Me.FromDTPicker.Value & "#)" & " and (BatteryDateChanged <= #" & Me.ToDTPicker.Value & "#));"
Just a side note, your comparison operators are the same. I think you want it to say something like (remember the "#" symbols):
...WHERE (Field1 >= #Date1# AND Field1 < #Date2#);
Hope that helps!

SQL Select statement wont return char fields only numeric fields

I have been racking my brain over this all day today.
I have the following ASP code that uses a Request.Querystring input from a dropdown box
to launch a select statement. The querystrinch does show in the ?= URL but will only work on
columns in the Microsoft SQL DB that are numeric. I cant lookup names or simple 3 character fields.
CODE:
If Request.QueryString("m") > 0 Then
filterID = Request.QueryString("m")
filterColmn = "imDegree"
Else filterID = 0
End If
If filterID > 0 Then
SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = " & filterID & ")"
End If
End If
I understand that this select statement as a sub select stament in it but I cant even get a staight reuturn from my DB. The select statement references the same view that populates the main asp page that loads before and the shows fine?
When you pass a string to SQL Server, you need to surround it with single quotes.
When you pass a number, you don't use the quotes.
So, when you say (summarizing)
SELECT * FROM table WHERE filterColumn = filterID
you should be sending a number.
To match a string:
SELECT * FROM table WHERE filterColumn = 'filterID'
This assumes that you have solved any other problems mentioned by the commenters about whether you even have a value in the filterID variable. I heartly concur with the recommendation to use parameterized queries.
Edit: The single quotes go inside the double quotes.
SQlQuery = "SELECT * FROM v_InternImport
WHERE iID IN (SELECT iID FROM v_InternImport
WHERE " & filterColmn & " = '" & filterID & "')"