Access Date Parameters - Date Range Prompt Error - sql

I have an Access 2007 report that prompts for a range of dates. It is using the SQL Query:
SELECT Calls.CallID, Contacts.County, Calls.ContactID, Calls.Date, Calls.Subject, Calls.Notes, Calls.Time FROM Contacts INNER JOIN Calls ON Contacts.[ContactID] = Calls.[ContactID] WHERE (((Calls.Date) Between [From date: ] And [To date: ]));
This works for most dates but I am getting an error when using the dates 07/01/2009 and 06/14/2010.
This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables. (Error 3071)
I have confirmed that none of the Calls.Date values are null. Is there some better way to prompt the user for the date range?

The best way to get parameters from a user is with a form. You can refer to the form in the query, for example:
Between Forms!frmDates!FromDate And Forms!frmDates!ToDate
It will make life easier for you, because you can evaluate the input before running the query. It will also make life a lot easier for the user, in that you can take advantage of the calendar that attaches to date data types in Access 2007 & 2010.

Related

Access SQL Query using BETWEEN Statement and dates from a form

I'm probably missing something basic here, but I can't for the life of me get this working.
I have a database that is tracking when certain projects are completed, and I want to be able to show in a list the completed projects between a date range.
The date range to check between is set by the user on a form.
I have built a query in Access:
SELECT Logs.Completed
FROM Logs
WHERE Logs.Completed BETWEEN Forms!UIBrowseCompleted!Text53 AND Forms!UIBrowseCompleted!Text55
ORDER BY Logs.Completed;
I have got the dates formatted in the text box so they are in #MM/DD/YYYY# format (I have manually put these dates direct in the query and this works) but when I run the query I get the following error:
This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables.
I have tried modifying the query to take the # out of the text fields in the form, and including ' around the Forms!UIBrowseCompleted!Text53 but I've still not got any joy from it.
has anyone had this issue before, or can anyone point me in the right direction.
Thanks
Do you want MS Access query or SQL query?
If you want MS Access query then you can try with following
SELECT Logs.Completed
FROM Logs
WHERE Logs.Completed >= Forms!UIBrowseCompleted!Text53 AND Logs.Completed <= Forms!UIBrowseCompleted!Text55
ORDER BY Logs.Completed;
between query will take time normally we use >= and <= to check date range
like
>= Forms!UIBrowseCompleted!Text53 AND Logs.Completed <= Forms!UIBrowseCompleted

Constructing an sql Query to get records betwen two dates

I'm trying to filter out and report records in a database that fall between a specified date range. I'm there are other threads here on how to do something similar, but my dates are stored as date timestamps (which is why I think the issue is arising)
My current query is as follows:
"SELECT * FROM JOURNAL WHERE Date_Time>'10/10/2013 00:00:00'"
(Note that journal is the name of the table I'm pulling the data from and date_time is the field in which the date is stored. I'm aware the query doesn't quite do what I want it to yet, but I was just testing out a simpler case at first.)
When I run this query (as part of an excel macro), excel reports that it can't find any records even though I know their are records past this date. Does anyone know how to do this properly?
Edit: I've got it, it was an issue unrelated to the query (something else in the macro) Thanks so much for the help (changing the date format worked)
have you tried other date format? like this:
"SELECT * FROM JOURNAL WHERE Date_Time>'2013-10-10:00:00:00'"
A simple between statement is what you need:
SELECT * FROM JOURNAL WHERE Date_Time between '10/10/2013 00:00:00' and '[otherdate]'
You need to run this to check for one important thing: If the server is running the BETWEEN as inclusive or not. If it's inclusive, both dates are included. If not, the range will begin either before or after one or both.
I've seen SQL servers that are the same in every respect actually treat this condition differently. So it's a good idea to check that.

SQL - User input in query

I have this. "Detail all films shown by the club between any two given dates, inputted by the user. For example a club member must be able to input a start date and an end date for the parameters for the query"
Now, how would I go about doing the user input? Only way I can think of would to be using php or something with a html form getting the values and then submitting them as variables in the query. However, that's not what is needed. So, how is this done so the query would ask for values? Or can't you?
My query so far looks like so.
SELECT film.title, film.desc, show.sdate, show.fdate
FROM film
INNER JOIN show
ON film.ID=show.filmID
WHERE sdate = '&userstart' AND fdate = '&userend'
How do I go about with the user input? Also, is the query correct? I have no way of testing, I only have a design not an implementation.
Thanks a lot
Edit: Using Windows system, MS SQL Server.
Here's the code for a stored procedure:
CREATE PROCEDURE SomeName(#UserStart DATETIME, #UserEnd DATETIME)
AS BEGIN
SELECT somestuff
FROM sometable
WHERE somedate BETWEEN #UserStart AND #UserEnd
END
#Kyle93 -
Looking at your WHERE Clause:
WHERE sdate = '&userstart' AND fdate = '&userend'
This will only get you Films that had a sdate(Start Date?) equal to the date value entered.
You might want to use Greater than, Less Than operators....
Such as:
WHERE sdate <= '&userend' AND fdate >= '&userstart'
(Note comparing sdate to UserEnd Date to make sure Film Showing started EARLIER than the UserEnd Date...etc)
This way - when a show starts OR ends within the date range - it will be selected.
Are you familiar at all with LINQ? It's a way to make db calls from c#.
-- I would handle this with HTML as you thought, and use Javascript/Ajax to reference c# code that uses LINQ for db calls. Might be a bit complicated however, if you're not familiar with much of that. I can recommend good tutorials if interested tho.

Extracting hour value from datetime column using DATEPART function

I'm trying to extract the numerical hour value from a column that contains time formatted as DateTime. For example, here are a couple of records from that column:
Time Aired
4:20:00 PM
12:51:00 PM
3:17:00 PM
3:24:00 PM
From this column I'm trying to extract 4, 12, 3, 3, etc. The DATEPART function appears to be a good option for this. However, when I try to use that function as shown below I'm prompted to enter a parameter for Hour. This leads me to believe I'm implementing DATEPART incorrectly. Can someone spot what the problem may be? Could the problem be that my datetime formatted column contains time values only?
SELECT DATEPART(hour, [Time Aired]) AS Foo
FROM DRTV_CentralOnly
WHERE [Time Aired] <> null;
This documentation shows that the interval part (hours) should be enclosed in quotes and it should be h, not hours; therefore, try this:
SELECT DATEPART("h", [Time Aired]) AS Foo
FROM DRTV_CentralOnly
WHERE [Time Aired] is not null;
My other question would be, aren't you supposed to write WHERE [Time Aired] is not null ?
You can use HOUR function instead of DATEPART.It gives hour numbers irrespective of AM/PM
SELECT HOUR([Time Aired]) AS Foo
FROM DRTV_CentralOnly
WHERE [Time Aired] <> null;
There are several ways you can extract only the number of hours from an MS Access Date value in a query expression a few ways.
Here are some of the methods:
DatePart("h", [yourFieldName]) 'returns a variant (Integer)
Format([yourFieldName],"h") 'returns a variant (String)
Hour([yourFieldName]) 'returns a variant (Integer)
In Access, I prefer the last method because it's short and clear.
Based on the question, I suspect you were looking at the documentation for the SQL Server DATEPART function which has some subtle differences.
Don't make the mistake of thinking that SQL is all the same. There are similarities but the syntax is not always interchangeable, especially when talking about MS Access. When searching for answers about Access, I always include mc access as part of my Google search query, and even still, when you find a potential answer, confirm that the page you're looking at was actually written for Access.
Your NULL problem
There's something you didn't ask for help for, but that you need help with! :) Indeed this is an old post, so you must have either figured out your mistake, or you're still stuck on it, or the company has been putting out incorrect reports for the last 6 years.
[myFieldName] Is Not Null is not the same as [myFieldName] <> Null.
The short explanation is that Null is not a value. Null can things around it. It's not a zero, it's not a '' empty string, and it's not a ZLS (zero-length-string).
The way you were using the <> NULL criteria it's likely your query was returning no records because of the incorrect syntax.
Examples:
For example: what result do you think this simple equation will produce?
(Null+2)*3
...if you said 6, you're wrong!
The result is: NULL. Basically, anything that touches NULL becomes NULL.
One more example. Run this in VBA:
If Null = Null Then MsgBox "Null equals Null." Else MsgBox "Null does NOT equal Null."
...you might not get the answer you'd expect!
For accuracy, all operators must be used the way they were intended, including the use of Is and Is Not operators with the NULL Statement.
More Information:
Office Support : DatePart Function (Access Query or VBA)
Office Support : Format Function (Access Query or VBA)
Office Support : Hour Function (Access Query or VBA)
Allen Browne : Common Errors with Null
Red-Gate : How to get NULLs Terribly Wrong in SQL Server
TechRepublic : 10 tricks for handling Null values in Microsoft Access
Wikipedia : Null (mathematics)
MSDN: Is Operator
Preparing for Unexpected Data:
This is actually only barely related, but made me LMAO because I never woudl have thought to prepare for this, and I figured I ought to share:
...which, in return, reminds me of that annoying little kid, Bobby Tables.

How can I make MS Access Query Parameters Optional?

I have a query that I would like to filter in different ways at different times. The way I have done this right now by placing parameters in the criteria field of the relevant query fields, however there are many cases in which I do not want to filter on a given field but only on the other fields. Is there any way in which a wildcard of some sort can be passed to the criteria parameter so that I can bypass the filtering for that particular call of the query?
If you construct your query like so:
PARAMETERS ParamA Text ( 255 );
SELECT t.id, t.topic_id
FROM SomeTable t
WHERE t.id Like IIf(IsNull([ParamA]),"*",[ParamA])
All records will be selected if the parameter is not filled in.
Note the * wildcard with the LIKE keyword will only have the desired effect in ANSI-89 Query Mode.
Many people mistakenly assume the wildcard character in Access/Jet is always *. Not so. Jet has two wildcards: % in ANSI-92 Query Mode and * in ANSI-89 Query Mode.
ADO is always ANSI-92 and DAO is always ANSI-89 but the Access interface can be either.
When using the LIKE keyword in a database object (i.e. something that will be persisted in the mdb file), you should to think to yourself: what would happen if someone used this database using a Query Mode other than the one I usually use myself? Say you wanted to restrict a text field to numeric characters only and you'd written your Validation Rule like this:
NOT LIKE "*[!0-9]*"
If someone unwittingly (or otherwise) connected to your .mdb via ADO then the validation rule above would allow them to add data with non-numeric characters and your data integrity would be shot. Not good.
Better IMO to always code for both ANSI Query Modes. Perhaps this is best achieved by explicitly coding for both Modes e.g.
NOT LIKE "*[!0-9]*" AND NOT LIKE "%[!0-9]%"
But with more involved Jet SQL DML/DDL, this can become very hard to achieve concisely. That is why I recommend using the ALIKE keyword, which uses the ANSI-92 Query Mode wildcard character regardless of Query Mode e.g.
NOT ALIKE "%[!0-9]%"
Note ALIKE is undocumented (and I assume this is why my original post got marked down). I've tested this in Jet 3.51 (Access97), Jet 4.0 (Access2000 to 2003) and ACE (Access2007) and it works fine. I've previously posted this in the newsgroups and had the approval of Access MVPs. Normally I would steer clear of undocumented features myself but make an exception in this case because Jet has been deprecated for nearly a decade and the Access team who keep it alive don't seem interested in making deep changes to the engines (or bug fixes!), which has the effect of making the Jet engine a very stable product.
For more details on Jet's ANSI Query modes, see About ANSI SQL query mode.
Back to my previous exampe in your previous question. Your parameterized query is a string looking like that:
qr = "Select Tbl_Country.* From Tbl_Country WHERE id_Country = [fid_country]"
depending on the nature of fid_Country (number, text, guid, date, etc), you'll have to replace it with a joker value and specific delimitation characters:
qr = replace(qr,"[fid_country]","""*""")
In order to fully allow wild cards, your original query could also be:
qr = "Select Tbl_Country.* From Tbl_Country _
WHERE id_Country LIKE [fid_country]"
You can then get wild card values for fid_Country such as
qr = replace(qr,"[fid_country]","G*")
Once you're done with that, you can use the string to open a recordset
set rs = currentDb.openRecordset(qr)
I don't think you can. How are you running the query?
I'd say if you need a query that has that many open variables, put it in a vba module or class, and call it, letting it build the string every time.
I'm not sure this helps, because I suspect you want to do this with a saved query rather than in VBA; however, the easiest thing you can do is build up a query line by line in VBA, and then creating a recordset from it.
A quite hackish way would be to re-write the saved query on the fly and then access that; however, if you have multiple people using the same DB you might run into conflicts, and you'll confuse the next developer down the line.
You could also programatically pass default value to the query (as discussed in you r previous question)
Well, you can return non-null values by passing * as the parameter for fields you don't wish to use in the current filter. In Access 2003 (and possibly earlier and later versions), if you are using like [paramName] as your criterion for a numeric, Text, Date, or Boolean field, an asterisk will display all records (that match the other criteria you specify). If you want to return null values as well, then you can use like [paramName] or Is Null as the criterion so that it returns all records. (This works best if you are building the query in code. If you are using an existing query, and you don't want to return null values when you do have a value for filtering, this won't work.)
If you're filtering a Memo field, you'll have to try another approach.