Access VBA Criteria of AND and & - ms-access

I am running the following query in Access VBA
Case "Customer Name"
strSQL = "SELECT CustomerID, Customer_Name, Industry FROM TBLCUSTOMERSNEW WHERE ucase(Customer_Name) Like '*" & UCase(tempStr) & "*'" & " ORDER BY Customer_Name"
Me.lstSearchResults.ColumnCount = 4
Me.lstSearchResults.ColumnWidths = "1cm;7cm;12cm;"
Is it possible to amend this query so that when the value being searched for (tempStr) contains a "&" the records returned also contain records where customer_name contains "and", and vice versa?

Just thought up a simple alternative not using any IF logic for you.
SELECT customerid,
customer_name,
industry
FROM tblcustomersnew
WHERE Replace(Ucase(customer_name), "&", "AND") LIKE '*" & Replace(UCase(tempStr), "&", "AND") & "*'" & "
ORDER BY customer_name
That should do it.

Related

Insert a value into a table while creating a record in another table

I'm out of my league on this... Another developer before me did something similar to what I want to do by adding a value in a table while updating another table. However, he was running updates as well as inserting, and his primary key was text. Mine PK is integer. Here's his code (works great) that I am trying to reverse engineer and apply to my situation:
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT ReportPK FROM
ACIST_MobilePipelineReportReviewed WHERE ReportPK = '" & ReportPk & "') " &
_
" UPDATE ACIST_MobilePipelineReportReviewed set Status = 'Approved'
WHERE ReportPK = '" & ReportPk & "'" & _
" ELSE " & _
" INSERT INTO ACIST_MobilePipelineReportReviewed ([ReportPK],
[PipelineUID],[ReportDate],[ReportInspector],[Status]) VALUES (" & _
"'" & ReportPk & "','" & Me!PipelineUID & "','" & Me!ReportDate & "','"
& Me!ReportInspector & "','Approved')"
End Sub
Here's what I'm doing: I have a combo box on a form called FacilityEntryF. That form is tied to my FacilityT table. I am selecting "CampaignID" from the CampaignT table and adding it to the FacilityT using that combo box in the aforementioned form. No biggie there... Works great.
The FacilityT has many columns of which I have [FacilityID] which is the primary key and is an autogenerated integer. It also has a column for [CampaignID] which is a foreign key from the CampaignT table.
After adding the CampaignID and starting a new FacilityID in FacilityT, I also want to create a new record in my CampaignFacilityParticipationT table. That table consists of only three columns: CampaignFacilityParticipationID, CampaignID, ParticipantFacilityID. I want to take the new [FacilityID] and the [CampaignID] I added to that table and insert them into the CampaignFacilityParticipationT table (FacilityID goes into the ParticipantFacilityID column). Here's the code below that didn't work (which I'm not surprised because I don't know what I'm doing):
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID =
" & FacilityID) " & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID]) VALUES (" & _
"" & CampaignFacilityParticipationID,'" & Me!CampaignID," & Me!ParticipantFacilityID, CampaignID)"
End Sub
Using MS Access 2013 with Microsoft SQL backend.
Thanks!!!
Concatenation is not correct. If apostrophes are needed to delimit parameters then make sure they are used consistently. Normally in Access, apostrophes would only be used for text fields, # for date/time and nothing for number. Maybe because backend is MS SQL apostrophes are needed for all field types? Why do you repeat CampaignID in VALUES clause?
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID = '" & Me!FacilityID & "')" & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID])" & _
" VALUES ('" & Me!CampaignFacilityParticipationID & "','" & Me!CampaignID & "','" & Me!ParticipantFacilityID & "')"
Is it possible for you to use a subform on FacilityEntryF on which you select the CampaignID? That will eliminate the need for this code.

Requerying subform only work sometimes

I am trying to requery a subform which diplays customer details.
I am sure my sql works as the subform works fine when not influenced by the main form.
Private Sub btnSearch_Click()
Dim sql As String
sql = "SELECT tblCustomer.[Job ID], tblCustomer.[Customer Name], tblCustomer.[Street Name], tblCustomer.Area, tblAppointments.[Appointment Date] " _
& "FROM tblCustomer " _
& "LEFT JOIN tblAppointments ON tblCustomer.[Job ID] = tblAppointments.[Job Number].Value " _
& "WHERE [Customer Name] LIKE '*" & Me.txtKeywords & "*'" _
& "OR [Job ID] LIKE '*" & Me.txtKeywords & "*'" _
& "OR [Street Name] LIKE '*" & Me.txtKeywords & "*'" _
& "OR [Area] LIKE '*" & Me.txtKeywords & "*'" _
& "OR [Appointment Date] LIKE '*" & Me.txtKeywords & "*'" _
& "ORDER BY tblAppointments.[Appointment Date];"
Me.subCustomerList.Form.RecordSource = sql
Me.subCustomerList.Form.Requery
End Sub
The debugger shows an error at the following line:
Me.subCustomerList.Form.RecordSource = sql
I also get the error message
object or class does not support set of events
Consider parameterization with a stored query for several reasons in your case:
Helps avoid syntax issues like what you may have since Access will not allow you to save a query with syntax errors if using the GUI query designer;
Better maintainability than a concatenated SQL string which requires single/double quote enclosure and you abstract data from code;
The Access engine compiles stored queries to best execution plan so will be more efficient than a VBA called SQL string (i.e., use index on JOIN).
SQL (save as a query object with parameter to be referenced by name in VBA)
PARAMETERS txtKeywordsParam TEXT(255);
SELECT c.[Job ID], c.[Customer Name], c.[Street Name], c.Area, a.[Appointment Date]
FROM tblCustomer c
LEFT JOIN tblAppointments a ON c.[Job ID] = a.[Job Number]
WHERE c.[Customer Name] LIKE txtKeywordsParam
OR c.[Job ID] LIKE txtKeywordsParam
OR c.[Street Name] LIKE txtKeywordsParam
OR c.[Area] LIKE txtKeywordsParam
OR a.[Appointment Date] LIKE txtKeywordsParam
ORDER BY a.[Appointment Date];
VBA
Private Sub btnSearch_Click()
Dim qdef As QueryDef
Dim rst As Recordset
' OPEN QUERY AND BIND PARAM
Set qdef = CurrentDb.QueryDefs("mySavedParamQuery")
qdef!txtKeywordsParam = "*" & Me.txtKeyword & "*"
' ASSIGN QUERY RESULT TO RECORDSET
Set rst = qdef.OpenRecordset()
' APPLY RECORDSET TO FORM
Set Me.subCustomerList.Form.Recordset = rst
Set qdef = Nothing
End Sub
I created a new subform and copied the one that did not work and everything seems to be running well.

Retrieve two database column fields in one textbox VB.NET MySQL

i have this search function to search for Firstname Middlename individually with their own CheckBox, this thing came to my mind if i want to search for Firstname and Middlename together in one Textbox with space of course and tried to use SELECT statement with CONCAT, but it didn't work.
it looks like this one:
If CheckBox1.Checked And CheckBox2.Checked Then
SQL = "SELECT * from student where CONCAT(fname,"" "", mname) like '%" & TextBox1.Text & "%'"
End if
Try this:
If CheckBox1.Checked And CheckBox2.Checked Then
SQL = "SELECT * from student where CONCAT(fname,' ', mname) like '%" & TextBox1.Text & "%'"
End if
EDIT
SELECT * FROM student WHERE MATCH (fname, mname) AGAINST ('+" & TextBox1.Text & "* +" & TextBox1.Text & "*' IN BOOLEAN MODE)
Might be this will give you the desired result

VBA Access - Multiple Tables count by date

We'd like to count from an Access database that has multiple tables - about 50.
We need to count from 1 column in each table that is 'QCPASS' This is a check box - if a product passed the box was checked if failed then not. We need to count both for EACH table, also allowing the user to specify a date range from a date column that exists in every table.
I've tried this with a query but I am told the query is unable to select, count and do the date range. Any VBA help would be great.
Exporting to Excel would be great, but any results would be fine. Here is the query I created that counts in a column from each table passes and failures. I can't iterate with a query either, so VBA seems the way to go:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
You can traverse the full TableDefs collection in your database, and create a query using VBA.
A word of warning: The TableDefs collection has the Access database system tables, so you need to skip this. A way I suggest you is to check for a specific table name prefix (it is noted in the code below).
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
Notice that you can define any valid query you want. Take this as a hint, and tweak it to fit your specific needs.
Hope this helps you
Adressing #HansUp comment, if you need to filter your data by date, you have two options:
Include the where condition on every select created by the procedure
Include the date field in your query and group by it, and create a second query to filter the data you need from the created query.
I would personally go with option 1, and here is a sample code:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
The reason I use cDbl(d0) is because Access dates are sensitive to regional settings, and I've had a lot of headaches dealing with it. Access (and many other Microsoft products) store dates as floating-point numbers (the integer part is the date, and the decimal part is the time).
Another word of warning: If your dates don't include time, then the between condition will work. But if they do include time, then I recommend you change the where condition to this:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"

Crosstab query with date criteria

I have created a crosstab query as below
TRANSFORM Nz(Sum([debit]*[GeneralExpenses]),0) AS mOmomeya
SELECT Expenses.sName, Expenses.ArName
FROM (GL INNER JOIN Expenses ON GL.ID = Expenses.glID) INNER JOIN Transactions ON GL.GL = Transactions.GL
GROUP BY Expenses.sName, Expenses.ArName
PIVOT Month([ddate]);
what I want to do is to add a criteria to the [dDate] field from a form text input to match the date that I entered, but I received error while doing this as below
any idea what's wrong?
Hmmm, there definitely seems to be something a little bit different about crosstab queries. The straight SELECT query...
SELECT expenses.*
FROM expenses
WHERE (((expenses.ddate) Between [Forms]![main]![DateFrom] And [Forms]![main]![DateTo]));
...works fine, but the crosstab query...
TRANSFORM Sum(expenses.expenses) AS SumOfexpenses
SELECT expenses.onduty
FROM expenses
WHERE (((expenses.ddate) Between [Forms]![main]![DateFrom] And [Forms]![main]![DateTo]))
GROUP BY expenses.onduty
PIVOT Month(ddate);
...fails with the error message you cited. One workaround would be to rebuild the SQL for the query before using it:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("yourCrosstab")
qdf.SQL = _
"TRANSFORM Nz(Sum([debit]*[GeneralExpenses]),0) AS mOmomeya " & _
"SELECT Expenses.sName, Expenses.ArName " & _
"FROM (GL INNER JOIN Expenses ON GL.ID = Expenses.glID) INNER JOIN Transactions ON GL.GL = Transactions.GL " & _
"WHERE (((ddate) " & _
"Between #" & Format(CDate([Forms]![main]![DateFrom]), "yyyy-mm-dd") & "# " & _
"And #" & Format(CDate([Forms]![main]![DateTo]), "yyyy-mm-dd") & "#)) " & _
"GROUP BY Expenses.sName, Expenses.ArName " & _
"PIVOT Month(ddate);"
Set qdf = Nothing
DoCmd.OpenQuery "yourCrosstab" '' or whatever you want to do with it
The problem is that crosstab querys require the form parameter for each form. Right click on gray space and select parameter. Put in the forms and data type.