Select records of last 12hours vb.net/MS ACCESS - vb.net

I am vb.net newbie and working on a program which will be used as a daily-worklog. As backend I use MS ACCESS. I store the "datetime.utc.now" time in a field (type:date/time) of MS Access.
This is shown in the database like: dd.mm.yyyy hh:mm:ss
I want to see all entered items of the last 12 hours. I used many different ways, but I´m not able to fix it.
My preferred / logical (for me :-)) way to do this was:
add the parameter:
mycommand.SelectCommand.Parameters.AddWithValue("date12",OleDbType.DBTimeStamp).Value = DateTime.UtcNow.AddHours(-12)
Query the database
select * from complaints where entrydate >= #date12;
But I can't figure out why it doesn't work.
Failure message = "data types in criteria expression incompatible"
I assume the problem is the different time formats, but I'm not sure and I have no clue how I could fix it.

MS Access does not use named parameters. You use a ? for all of the placeholders in the SQL statement. You still can and should give the parameter object a name, but the value is matched to the placeholder based on position in the Parameters collection and query string rather than name.
SQL:
"select * from complaints where entrydate >= ?;"
VB:
mycommand.SelectCommand.Parameters.Add("date12",OleDbType.Date).Value = DateTime.UtcNow.AddHours(-12)
Do NOT settle for hard-coding the parameter value. What you can do is use SQL expressions to determine the date value, and avoid both parameters and string concatentation:
select * from complaints where entrydate >= DATEADD('h', -12, Now())

You can change the type to OleDbType.Date or hardcode the query:
select * from complaints where entrydate >= ( Now() - 0.5 )
Trouble inserting DateTime into Access with OleDb
As a side note, most value types are generally safe to hardcode:
"select * from complaints where entrydate >= " & DateTime.UtcNow.AddHours(-12).ToOADate()

Related

How do I use LIKE with a date field in MS Access with a NULL value

I have an application that allows partial date searches. It doesn't specify what the date part is. if someone puts in "20", it could be part of the year or a day of the month.
The application uses an Access databases where some of the date fields have NULL values.
I am trying to write a query with [date field] LIKE {date criteria}.
What I started to do is convert the date field to a string using cstr(datefield), but the NULL values are giving #error values.
SELECT * ,cstr(datefield) AS strdate FROM table1
Access has the ISNULL function, but it only takes one parameter which returns true or false, as opposed to the ISNULL function in SQL Server, which takes two parameters, the second being the value to use if the first parameter is null.
I supposed I could add "AND datefield IS NOT NULL" to the end, but I wanted to ask if there were any other possible solutions to this.
Then when I did finally get to the query itself, it didn't return any results.
SELECT * ,cstr(datefield) AS strdate
FROM table1
WHERE scan_date IS NOT NULL
AND cstr(datefield) LIKE '%20%'
How would I do a LIKE query against a date field in access?
You can use the function Nz():
SELECT * , Nz(datefield) AS strdate
FROM table
WHERE Nz(datefield) LIKE '*20*'
But you should know that the wildcard operator to use in Access is not % but * and this is the reason that you don't get any results.

Retrieve data from a certain date in SQLite

I'm having a problem retrieving data from my SQLite database based on a certain month. I've looked around and saw people using strftime in a WHERE clause and I've tried this, but I'm getting mixed results. I'm either getting all the data in the database regardless of the date, or I'm getting no results but no errors or exceptions are appearing. I'm wondering if anyone would have a solution to this?
In my table I have a column called "Date" which is TEXT (string in my Model class) and I'm saving data in the format of dd/MM/yyyy, but after reading around I thought it was maybe the format I'm saving it as that was causing the problem so I tried with yyyy-MM-dd and dd-MM-yyyy also, but it doesn't solve the problem.
I've also tried different select statements to see if that helped. This returns all data rather than only data from January;
var selectStmt = "SELECT * FROM SleepTrackerModel WHERE strftime('%m', '01')";
SleepHistory = _dbHelper.Read<SleepTrackerModel>(selectStmt);
The following returns no data;
var selectStmt = "SELECT * FROM SleepTrackerModel WHERE strftime('%m', 'Date') = '01'";
SleepHistory = _dbHelper.Read<SleepTrackerModel>(selectStmt);
I've also tried listing all column names rather than using the *. I can't really find any help other than the way I've been using. SleepHistory is an ObservableCollection. What I'm trying to do is when the user clicks a button representing each month of the year, they'll be shown the data for that month.
Any help would be great. Thanks.
In SQL, Date is a column name, while 'Date' is just a string.
strftime('%m', 'Date') tries to interpret that string as a date value, which fails.
An SQL expression like this checks for dates in January:
... WHERE strftime('%m', Date) = '01'

Date criteria in sql query, in R

I'm having a problem refining an SQL query within R. I'm querying an Microsoft Access database. I'm not sure if this is an SQL problem or an R problem. I use RODBC to establish a connection, then I'm trying to limit a query by just getting results from 2000-1-1 onward.
When I query the entire field, I used str() to determine the exact date type so I could create a comparison variable. So, I got something like
wholeqry <- sqlQuery(channel,
paste("select DATE, OTHERFIELD from DB", sep=""))
(testdate <- wholeqry[1,1])
str(testdate)
This returns:
"1984-11-29 EST"
POSIXct[1:1], format: "1984-11-29"
Ok, so I format a variable so I can compare it to this:
start <- as.POSIXct(strptime("2000-01-01", format="%Y-%m-%d"), tz = "EST")
Then I check to see if they are indeed comparable with logic operators:
testdate < start
start < testdate
The results, as expected:
TRUE
FALSE
Ok, now I feel like I'm ready to do my query. I use paste() to pass start as a variable in the sql statement:
qry <- sqlQuery(channel,
paste("select DATE, OTHERFIELD from DB where DATE >=", start, sep=""))
But, when I check qry, it's the whole field minus two entries. The really confusing part to me is if I check the same entry in my new qry, I get the same date, and can compare it to my start variable, and still get the correct logic results. That is:
(testdate <- qry[1,1])
testdate < start
start < testdate
Gives the results:
"1984-11-29 EST"
TRUE
FALSE
So, while two records were kicked out by the comparison, the rest weren't, even though if I manually compare them, they should be rejected. I considered that the format of the date field may not be uniform, as some entries have time zone EDT as opposed to EST, but if I check those entries against my start date, I still get the correct logic results.
I just had this issue and solved it the following way. Access requires dates to be surrounded by the '#' symbol. The following query should work:
qry <- sqlQuery(channel, "select DATE, OTHERFIELD from DB where DATE >= #2000-01-01#")

Change date format in SQL for ASP

I have the following code:
"SELECT top 1 * FROM CensusFacility_Records WHERE Division_Program = 'Division 1' AND JMS_UpdateDateTime = '" & date & "'"
The date format in column JMS_UpdateDateTime is:
8/22/2013 12:00:07 AM
How can I make sure that my "date" in the query is converted to the correct time format?
My date variable in my SQL query is a real/date time. I would like for it to match the format within the JMS_UpdateDateTime field.
If your database table is small enough, you can cast the value to an actual datetime inside your query, and pass the value in as a datetime parameter, so you're comparing dates instead of comparing strings.
If your table has a decent amount of records, don't do this, because it will be a performance hog.
SELECT top 1 *
FROM CensusFacility_Records
WHERE Division_Program = 'Division 1'
AND cast(JMS_UpdateDateTime as datetime) = #dateParam
I believe SQL Server will be able to read the string that's in your database and automatically cast it properly, assuming your server settings are standard.
But in any case, use parameterized SQL instead of passing in a string like you've got.
The format of your SQL DateTime is actually a bit of a red herring here - it can be displayed in any way the front end (e.g. Management Studio) chooses. The important thing here is that your date variable is in an unambiguous format. With this in mind I'd recommend using the ISO 8601 date/time format, e.g. date.ToString("o") (assuming date is a DateTime).

Passing date parameters to Oracle Query in SSRS

I have an SSRS report that uses an Oracle datasource. I have a query;
select * from myTable t where
t.date between Date '2009-08-01' and Date '2009-08-04' + 1
This query works, both in Oracle and from SSRS. It gets all rows from myTable when the t.date column is between 08/01/2009 and 08/04/2009. The t.date column is of type Date()
Now, I want the dates to be parameters. So I changed the query to:
select * from myTable t where
t.date between Date :myDate and Date :myDate + 1
When I run this query in SSRS, it prompts me to enter a value for :myDate.
I tried 2009-08-01, '2009-08-01' both results in an oracle sql processing error: " Missing expression".
Any ideas?
If you insist on having one parameter (:myDate), using a with clause can make the process a bit cleaner. I'm not familar with the syntax you have in your example (i.e. the 'Date' like casting in the query), below is a SQL only implementation.
with
select TRUNC(TO_DATE(:mydate, 'yyyy-mm-dd')) p_date from dual as parameters
select t.*
from
myTable t,
parameters
where
trunc(t.date) between parameters.p_date and parameters.p_date + 1
Just because you have used :myDate twice doesn't mean that they are the same. They are placeholders, and since you have two placeholders you need two values.
This worked for me using SSRS:
SELECT t.*
FROM myTable t
WHERE t.date between :myDate AND to_date(:myDate + 1)
Have you tried making sure the parameter is a DateTime type (it is string by default) in the Report Parameters menu?
I had a similar problem with a much larger query, and I found that simply searching and replacing e.g. :mydate with TO_DATE(:mydate) was sufficient to solve the problem - the same date was then passed to every instance of TO_DATE(:mydate) in the query.
If you want a date range passed into the query, I would give the parameters different names e.g. :StartDate and :EndDate in the SQL and have separate parameters #StartDate and #EndDate in the report. This makes the SQL much clearer.
SSRS newer versions :parameter is not working, you need to use ? as below
below first two parameters date and third one text
select * from tasks where FINISH_DATE between ? and ?+1 and t2.TYPE = ?