Contains Syntax for SQL - sql

I'm at my wits end here, I'm trying to get this to work
Set rex2 = db.OpenRecordset(" Select count(*) from events where event_date >= #" & Format(last_week_start, "mm/dd/yyyy") & "# and maildate <= #" & Format(last_week_end, "mm/dd/yyyy") & "# and contains(event_type, ""1st call attempted"") and work_ID contains ""UNS"";")
where event_type is the column name in the database and work_ID is also the column name in the database. I've tried it in numerous ways i.e.
WHERE event_type contains ""1st Call Attempted"
etc but I'm having no luck.
I'd change my code but in event_type there are way too many 1st call attempted categories to list.
I'm also open to using a left statement ie
Where left(event_type, 18) = " 1st Call attempted"
Anything to get this sodding thing working
Please help me.

Perhaps you should use the LIKE operator. You'd need to do something like this:
... WHERE event_type LIKE '1st Call attempted%' ...
and similarly for work_ID.
This will match any string that starts with "1st Call attempted" and ends in whatever, since it's like a * wildcard. If you executed it in Access, then you'd use a * instead of a %, but in OLEDB you need to use a %.

Related

Use a parameter in SSRS for table_name

I have scoured the internet for options and the only one I have found that can do it is by using a $Proc however I am trying to avoid that.
I would think it would be pretty simple to use a parameter to select a different table depending on what the user chooses from a drop down.
Here it is:
- There are two tables the report needs to use,
* some_table_CY (current year table)
* some_table_STLY (same time last year table)
So I created a parameter that gives the user the option to select "Current_Year" or "Last_Year", depending on which one the user chooses the parameter would then be used in the select statement, something like this: "SELECT * FROM :pReportVersion"
However, it is not working. I need it to do this, not using a union since unioning these two tables causes HUGE performance issues and the query takes more than 4 hours to run which is not acceptable for a report that users need on request.
(This is querying oracle)
Use the Dataset expression and set it to:
="SELECT * FROM " & Parameters!ReportVersion.Value
For longer queries you may need to wrap each line with quotes, append with an ampersand and add a line feed:
="SELECT * " & VBCLRLF &
"FROM " & Parameters!ReportVersion.Value & VBCRLF &
"WHERE FIELD1 > 10 " & VBCRLF &
"AND FIELD2 = 'YES' "
you can still use the union..
Say you have a parameter called #year
set the available values to the following (specify values)
current year for label and 1 for value
last year for label and 2 for value
Then your dataset can be something like this:
select * from some_table_CY
where #year = 1
union all
select * from some_table_LY
where #year = 2

Using DCount in Access with multiple criteria

I am trying to count the number of records in a table which satisfy criteria for two different fields. Both fields are string values.
The first field is what type of Test appears e.g. 'Manometry'. I can get this field to work on it's own.
I experience a problem when trying to add the second criteria.
The second field is the TestID, which is in the format A_155_19, where 155 is the investigation number and 19 identifies the year it took place.
I would like to count all the manometry tests which occur in the current year.
DCount("[Test]", "Visits", "[Test] = 'Manometry'" & "[TestID] = *Right((Year(Date)), 2)'")
I am currently getting the error message 3075, which is missing syntax.
Any help would be greatly appreciated.
What about:
DCount("[Test]", "Visits", "[Test] = 'Manometry' And [TestID] Like " & SomeExpression)
You can use Format:
DCount("*", "Visits", "[Test] = 'Manometry' And [TestID] Like '*_' & Format(Date(), "yy") & "'")

SSRS lookup with datediff Incorrect result error showing in fields

I have to write again this problem. I am not an expert in SSRS.
I have been trying to resolve this issue. Even though the fields are all the same datatype am still getting error and incorrect time difference in the filed in some fields.
I do not know what am doing wrong. This is the code. Please find below screen shot also.
enter code =Datediff(DateInterval.Minute, Fields!health_start_date.Value, Lookup(Fields!flight_date.Value & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value) , Fields!FL_DATE.Value & Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value), Fields!ATD.Value, "DataSetAIMS") ) MOD 60 & " mins "
here
The scenario is that the two fields Health start date and ATD have two different dataset which shows time of flight differently but the time difference is always in minutes. What am trying to do is to compare the two table with their hour and date using lookup to find difference in minutes
Okay, I think I see the problem: you're really close and this stuff trips us all up on occasion. In the LOOKUP function, I think you are joining the two data sets based on:
flight_date = FL_DATE, and
register_number = REG, and
HOUR(health_start_date) = HOUR(ATD)
Which is fine, but the ampersand (&) just "concatenates" strings together, and (a) your strings don't actually match, and (b) HOUR is a number, not a string.
(a) The "date" in the first data set is DDMMYYYY, and in the 2nd it is DDMMYY. I.e., "05222018" is not the same as "052818", so your lookup will not work. It's possible that they are stored correctly as date fields in the database and so the comparison will work fine, but better to force them to match. For that I'd recommend formatting each of the date strings into a standard format, like "FormatDateTime(Fields!flight_date.Value, DateFormat.VBShortDate)".
(b) Should be easy, just add ".ToString" after the parentheses, like "DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString()".
(c) I'm assuming the register_number and REG are formatted the same.
Given all that, your new LOOKUP function might look something like this:
=Datediff(DateInterval.Minute,
Fields!health_start_date.Value,
Lookup(
FormatDateTime(Fields!flight_date.Value, DateFormat.VBShortDate) & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() ,
FormatDateTime(Fields!FL_DATE.Value, DateFormat.VBShortDate) & Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value).ToString()
, Fields!ATD.Value
, "DataSetAIMS")
).ToString() & " minutes"
However, I think you'd make your life easier by just doing that sort of calculation in the database layer, in the report query, something like:
SELECT
d1.FlightDate
, d1.RegisterNumber
, d1.HealthStartDate
, d2.ATD
, DiffInMinutes = DATEDIFF(MINUTE, d1.HealthStartDate, d2.ATD)
FROM DataSet1 d1
JOIN DataSetAIMS d2
ON CAST(d1.FlightDate AS DATE) = CAST(d2.FL_DATE AS DATE)
AND d1.register_number = d2.REG
AND DATEPART(HOUR, d1.health_start_date) = DATEPART(HOUR, d2.ATD)
This code certainly isn't exact, but hopefully it will get you pointed in the right direction!
Thanks Russel. I have accepted your answer. What I did was to remove the formatdate from the expression code and modify the query design code to convert to the same time date : the code below
=Datediff(DateInterval.Minute, Fields!health_start_date.Value, Lookup(Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() , Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value).ToString(), Fields!ATD.Value, "DataSetAIMS") ).ToString() MOD 60 & " mins "
or the below as well works :
=Datediff(DateInterval.Minute,
Fields!health_start_date.Value,
Lookup(
Format(Fields!flight_date.Value, "ddMMyy") & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() ,
Format(Fields!FL_DATE.Value, "ddMMyy") & Fields!REG.Value & DatePart(DateInterval.Hour,Fields!ATD.Value).ToString()
, Fields!ATD.Value
, "DataSetAIMS")
).ToString() MOD 60 & " minutes

Why doesn't my query use my criteria?

I have a db in Access and I'm trying to get a textbox to run my query and pass an other bounded textbox's value in as the criteria in DLookUp. I have the query running in design view and when I enter the criteria directly it returns the correct results. When I open the report it gives me the sum of all the possible rows. In other words it doesn't filter the rows.
I haven't used Access in about twelve years, thankfully, and everything I've done up to this point has been tutorial/example patchwork, but here it is...
SQL Query:
SELECT Sum(IIf(Attended=-1,1,0)) AS attendance
FROM Students_Classes_Attendance
WHERE (((CStr([Students_Classes_Attendance].[Class_Id]))=[classId]));
DLookUp as Control Source:
=DLookUp("[Total Attendance by Class]![attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
I'm lost at the moment. I'm guessing that the value isn't there before the query fires and since the criteria is an optional parameter that it's being passed null, but I would hope you'd get an error from that. Not that #Error is very meaningful anyway.
Does anyone know for certain the problem and the best way to correct it? Thanks.
Edit:
I did the changes recommended in the answer so now my DLookUp looks like...
=DLookUp("[attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
...still returns the total for all rows. Removing the criteria completely makes no difference either, which returns me to thinking it has something to do with the bound textbox not having a value.
DLookup uses the following syntax:
Syntax for numerical values:
DLookup("FieldName" , "TableName" , "Criteria = n")
Syntax for strings: (note the single apostrophe before and after the string value)
DLookup("FieldName" , "TableName" , "Criteria= 'string'")
Syntax for dates: (note the # before and after the date value)
DLookup("FieldName" , "TableName" , "Criteria= #date#")
I believe you just need to remove the table name from the first parameter. Try this:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = " & [Class_Id])
Keep in mind that if Class_Id is a Text Field, you need to surround it by single quotes:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = '" & [Class_Id] & "'")

MS Access multi field search with empty fields

I have a problem very similar to this one, but I just can't seem to solve it!
In MS Access (2003), I want to search a table based on entries in a number of fields, some of which may be empty.
I have:
text fields
date fields
integer fields, and
a memo field (but we can probably not bother searching this one if it is difficult).
They map onto a table exactly.
I am trying to create a query that will return matching rows when data is entered into one or more of these fields, but some fields can be left blank. How the heck do I do this?
A query like the one on the linked question works for text fields, but what do I do about the number fields, date fields (and possibly even the memo field)?
To give a clear example, the following code block works for TextField1, but not NumberField1:
PARAMETERS [Forms]![SearchForm]![FilterTextField1] Text ( 255 ), [Forms]![SearchForm]![FilterNumberField1] Text ( 255 );
SELECT Table1.[TextField1], Table1.[NumberField1], Table1.[TextField2], Table1.[TextField3], Table1.[DateField1], Table1.[DateField2], Table1.[DateField3]
FROM Table1
WHERE (Len([Forms]![SearchForm]![FilterTextField1] & '')=0 OR Table1.[TextField1] Like '*' & [Forms]![SearchForm]![FilterTextField1] & '*') AND (Len([Forms]![SearchForm]![FilterNumberField1] & '')=0 OR Table1.[NumberField1] Like '*' & [Forms]![SearchForm]![FilterNumberField1] & '*');
I do hope you can help. I'm sure I'm missing something really obvious, but for some reason my brain feels like it is leaking out of my ears at the moment.
Thank you!
If you need it, this is the basic design of the relevant entities:
Table1
SomePrimaryKeyWeDontCareAboutRightNow
TextField1
TextField2
TextField3
NumberField1
DateField1
DateField2
DateField3
MemoField1
SearchForm
FilterTextField1
FilterTextField2
FilterTextField3
FilterNumberField1
FilterDateField1
FilterDateField2
FilterDateField3
FilterMemoField1
You can check fo null values or cast to string
You could certainly spend a great deal of time crafting a huge and very hard to debug SQL query for this, or just jump into VBA and write some code to construct just the SQL you need.
VBA is there just for these kinds of scenario, where something is either impossible or becoming too complex to do otherwise.
With VBA, you can use an initial SELECT query that collect all the data, and then construct a WHERE clause based on the content of your search form to filter it.
For instance, I have a form like this, that allows the user to enter any criteria to filter a list of prices:
Some code to implement this could look like:
' Call this whenever the use click the Apply button '
Private Sub btApply_Click()
' Construct the filter '
Dim filter As String
If Not IsBlank(cbSupplierID) Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(SupplierID=" & cbSupplierID & ")"
End If
If Not IsBlank(txtPartNumber) Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(PartNumber LIKE '*" & txtPartNumber & "*')"
End If
If Not ckShowLocked Then
If Not IsBlank(filter) Then filter = filter & " AND "
filter = filter & "(NOT PriceLocked)"
End If
' ... code snipped, you get the jest ... '
' Now re-construct the SQL query '
Dim sql As String
sql = "SELECT * FROM Price"
If Not IsBlank(filter) Then
sql = sql & " WHERE " & filter
End If
SubForm.Form.RecordSource = sql
End Sub
It may seem like a lot of code, but each block only does one thing, and it's a lot easier to debug and maintain than cramming everything into a query.