Date and Time Formatting in VB.net and SQL Server - sql

I have a table in which data is been logged in 'yy/MM/dd HH:mm:ss' format and my regional setting is '2016-04-02 14:25:15' type. I want to get details in a following query but it is not populating any results
The query I used is
select
Date_time, alarm_id, alarm_message
from
table01
where
Date_time between '" & DateTimePicker5.Value & "' and '" & DateTimePicker6.Value & "'
I also tried using one function which I had written is
Private Function FormatDate(ByVal dat As String) As String
Dim FTDate As Date
FTDate = FormatDateTime(Convert.ToDateTime(dat), DateFormat.ShortDate)
FormatDate = Format(FTDate, "yy/MM/dd HH:mm:ss")
End Function
And used the same again in query as
select
Date_time, alarm_id, alarm_message
from
table01
where
Date_time between '" & formatdate(DateTimePicker5.Value) & "' and '" & formatdate(DateTimePicker6.Value) & "'
Please suggest appropriate answer make sure that I don't want to change my regional setting and on form load event. I've written the following code
DateTimePicker5.Format = DateTimePickerFormat.Custom
DateTimePicker5.CustomFormat = "yy/MM/dd HH:mm:ss"
DateTimePicker6.Format = DateTimePickerFormat.Custom
DateTimePicker6.CustomFormat = "yy/MM/dd HH:mm:ss"
The Table Is In Below Mentioned Format
**Datetime V1 P1**
16/08/29 19:12:24 10 STB-1
16/08/29 19:12:19 20 STB-1
16/08/29 19:12:18 30 STB-1
16/08/29 19:09:50 40 STB-1

Never ever ever EVER use string concatenation to put values into a query like that! It's practically begging to wake up one morning and find out your site was hacked six months ago.
The first thing you need to do is fix the schema, so that your date values are actually stored as DateTime columns. There are so many reasons for this, I can't even begin to describe them all. Just do it!
Once that's done, you build the query like this:
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Hey, look: it's a constant. Now that's not strictly necessary; I usually just use a normal Dim'd String value. However, I wanted to prove a point here: your SQL statement is set to use specific place holders that will never at any point have data in them. The values you provide for those #StartTime and #EndTime values will be completely separated and quarantined from your SQL command, such that no possibility for injection ever exists.
Once you have the SQL command string, you can use it like this (repeating the string definition so everything is in one place):
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(SQL, cn)
cmd.Parameters.Add("#StartTime", SqlDbType.DateTime).Value = DateTimePicker5.Value
cmd.Parameters.Add("#EndTime", SqlDbType.DateTime).Value = DateTimePicker6.Value
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
' ...
End While
End Using
End Using
Or if you're filling a DataTable:
Dim result As New DataTable()
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(SQL, cn), _
ad As New SqlDataAdapter(cmd)
cmd.Parameters.Add("#StartTime", SqlDbType.DateTime).Value = DateTimePicker5.Value
cmd.Parameters.Add("#EndTime", SqlDbType.DateTime).Value = DateTimePicker6.Value
ad.Fill(result)
End Using
Note that using this method, you never have to worry about your DateTime format. ADO.Net figures it out for you. It knows about .Net DateTime objects, and it knows about Sql Server DateTime columns, and it handles conversions between the two types naturally.

This is some what a tricky solution.
Since year kept as 'yy' in the backend,following are the assumptions.
if the year part of the database field is between 00 to 16 ,need to consider this as 2000 to 2016. for the remaining values script will consider year as 1917 to 1999 .
Can you try with the below script.
SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE
CASE WHEN LEFT(Date_time,2) between 00 and RIGHT(year(getdate()),2) THEN CONVERT(DATETIME,'20'+Date_time)
ELSE CONVERT(DATETIME,'19'+Date_time) END between '" & DateTimePicker5.Value & "' and '" & DateTimePicker6.Value & "'

You can use Convert function.
select
Date_time, alarm_id, alarm_message
from
table01
where
Convert(Datetime,Date_time) between Convert(Datetime,'" & DateTimePicker5.Value & "') and Convert(Datetime,'" & DateTimePicker6.Value & "')

Since:
Console.WriteLine(#1/31/2016 10:23:22 AM#.ToString("yy/MM/dd HH:mm:ss"))
returns 16/01/31 10:23:22
I guess that:
select
Date_time, alarm_id, alarm_message
from
table01
where
(Date_time >= '" & DateTimePicker5.Value.ToString("yy/MM/dd HH:mm:ss") & "' )
and (Date_time < '" & DateTimePicker6.Value.ToString("yy/MM/dd HH:mm:ss") & "')
will do the trick.
Notice that I've changed the between with simple compare conditions
Run this in SQL Server and check the results:
create table #dateTest (
testDate datetime
)
insert into #dateTest values ('2016-03-01')
select * from #dateTest
declare #fromDate datetime
set #fromDate = '2016-01-01'
declare #toDate datetime
set #toDate = '2016-03-01'
select
testDate
from
#dateTest
where
( testDate between #fromDate and #toDate )
-- 2016-03-01 00:00:00.000
select
testDate
from
#dateTest
where
( testDate <= #fromDate )
and ( testDate < #toDate )
-- No rows selected
drop table #dateTest

Related

Variable of date in a SQL query

Can you please help with implementation variable into SQL query in VBA? I am getting syntax error of date, timestamp or ODBC, DB2 ......thank you
Dim startdate As Date
Dim enddate As Date
startdate = InputBox(startdate, "YYYY-MM-DD")
enddate = InputBox(enddate, "YYYY-MM-DD")
I am trying to implement variable into where clause in the SQL statement:
where atindt>='" & startdate & "' and atindt<='" & enddate & "'
There is no reason to include startdate or enddate as arguments to InputBox
replace
startdate = InputBox(startdate, "YYYY-MM-DD")
enddate = InputBox(enddate, "YYYY-MM-DD")
by
startdate = InputBox("YYYY-MM-DD") 'perhaps with a more informative prompt
enddate = InputBox("YYYY-MM-DD")
and that part of the code will work as intended.

Database contains European dateformat but query searches on American date format

Well, I'm using an MS Access database and I have a field Date. In the property of this field I have specified that the format should be 'dd/mm/yyyy'. However, when I use queries on the field, it searches with the date format 'mm/dd/yyyy'. I have no idea why it's doing this because I thought the queries adapt to the field properties and I haven't been able to find a solution online. My location and timezone are set in Europe. This is the query that I used:
SELECT Count(*) AS Amount
FROM Plays
WHERE PersonID = 1001 AND RestaurantID = 101358 and Date = #7/6/2016#
So, in this query it doesn't search the 7th of June 2016 but the 6th of July 2016. Both PersonID and RestaurantID are set as numbers; Date is set as Date/Time. How do I fix it so the query searches as the date format 'dd/mm/yyyy' as well without having to use any sql functions everytime?
If your query is written in VBA, you MUST write the dates using m/d/y. That's it.
I tend to construct my SQL statements using Format(expr, "\#mm\/dd\/yyyy\#"). E.g:
const kUsDtFmt = "\#mm\/dd\/yyyy\#"
sSql = "SELECT * FROM myTable WHERE dtUpdated = " & Format(Date(), kUsDtFmt )
Note: "\" is the escape key in format strings, meaning that the next character is taken as is.
If you simply wish to filter on today's date, do this:
SELECT Count(*) AS Amount
FROM Plays
WHERE PersonID = 1001 AND RestaurantID = 101358 and [Date] = Date()
For other dates, use DateSerial which frees you from format considerations:
SELECT Count(*) AS Amount
FROM Plays
WHERE PersonID = 1001 AND RestaurantID = 101358 and [Date] = DateSerial(2016, 6, 7)
If you concatenate string expressions, use the ISO sequence:
Dim SomeDate As Date
SomeDate = DateSerial(2016, 6, 7) ' or any other date value.
DateString = Format(SomeDate, "yyyy\/mm\/dd")
SQL = "SELECT Count(*) AS Amount " & _
"FROM Plays " & _
"WHERE PersonID = 1001 AND RestaurantID = 101358 and [Date] = #" & DateString & "#"
Note please, that Date is a reserved word, thus may have to be bracketed as shown.
Welp, I eventually found a solution to the problem:
"SELECT COUNT(*) as Amount FROM Plays WHERE PersonID = " & Me.txtPersonID &_
" AND RestaurantID = " & Me.txtRestaurantID & " AND Date = #" & Month(Me.txtDate)_
& "/" & Day(Me.txtDate) & "/" & Year(Me.txtDate) & "#"
I expected some of your solutions to work but for some reason(s) they didn't. Anyhow, now the correct date is searched and the correct value is returned. Thanks for the time you spent helping me.
Use FormatDateTime with vbShortdate to make sure your date is formatted the way the system expects it to be and not the way humans like to see it.

VB.NET Access Datetime Querying Issue

I have a bunch of records in an Access db table with a datetime fields
e.g of records (2/2/2015 3:34:21 PM,2/2/2015 8:29:13 AM )
Problem is I need to run a query where I need all records for displayed to be ones that occurred on the same day regardless of the time. How to best structure this query?
I used 'Select * from table where thetime = 2/2/2015' and there was no result returned. I switched the date format to start with the year, no luck.
Any tips as to sql query syntax for Access will be appreciated. Thanks.
Date/Time values in Access always have both a date and time component, so a date literal like 2015-02-02 is equivalent to 2015-02-02 00:00:00. If you want all rows for that date, regardless of the time, you need to use a WHERE clause like
... WHERE thetime >= {that date} AND thetime < {the following day}
The proper way to do that in VB.NET is to use a parameterized query like this:
Using cmd As New OleDbCommand()
cmd.Connection = con ' an open OleDbConnection
cmd.CommandText =
"SELECT * FROM thetable " &
"WHERE thetime >= ? AND thetime < ?"
Dim targetDate As New DateTime(2015, 2, 2) ' example data
cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate
cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate.AddDays(1)
Using rdr As OleDbDataReader = cmd.ExecuteReader
Do While rdr.Read()
Console.WriteLine(rdr("thetime"))
Loop
End Using
End Using

SQL Server date between LIKE

Please help me how to insert LIKE % in date between. Example is:
SELECT *
FROM table
WHERE Date BETWEEN '" & startDate & "%'" AND '" & endDate & "%'"
So in this code where i should put LIKE so that data will appear?
example if i set like this
SELECT *
FROM table
WHERE Date LIKE '" & startDate & "%'"
it's working..LIKE meant read either startdate or %..for starting it will read %
Try this :
"Select (listOfFields)
FROM TABLE
where CONVERT(VARCHAR(25), Your_DATE, 126) BETWEEN 'Start_date%' AND 'EndDate%'";
Try something like this
SELECT * from table
WHERE CONVERT(VARCHAR, DateField, 120) BETWEEN '2010%' AND '2012%'
If the dates are of type string, you can't use BETWEEN*.
If the dates are of type date or datetime, you can't use LIKE.
*Actually between might work with text because b is between a and c but it will not return correct results with date strings.

vb.net date format from textbox > MS SQL query

I have a date column in a DB tabel that I want to query using a date taken from textbox.text. the user selects a date from the calendar in the format dd/MM/yyyy. I want to use that date to put into a query. How do i format the date to be able to query the database?
Dim datefrom As String =txtDateFrom.Text
Dim dateto As String =txtDateTo.Text
The query will look like this:
WHERE (tblClient.ClientID = " & ClientID & ") AND (tblBackupArchive.BackupDate BETWEEN '" + datefrom + "' AND '" + dateto + "')"
I'm using MS SQL Server btw. Any help most appreciated.
Jonesy
NEVER USE STRING CONCATENATION LIKE THAT TO BUILD YOUR QUERIES!!!
And yes, I did mean to yell, because date formatting is the least of your problems. Imagine what would happen in your current code if something entered the following into one of your date textboxes:
';DROP TABLE tblClient;--
Instead, use a parameterized query. That will fix your date issues and protect against sql injection attacks. Here's an example:
Dim sql As String = " .... WHERE tblClient.ClientID= #ClientID AND tblBackupArchive.BackupDate >= #DateFrom AND tblBackupArchive.Backupdate < #DateTo"
Using cn As New SqlConnection("your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#ClientID", SqlDbType.Int).Value = ClientID
cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = DateTime.Parse(txtDateFrom.Text)
cmd.Parameters.Add("#DateTo", SqlDbType.DateTime).Value = DateTime.Parse(txtDateTo.Text).AddDays(1)
cn.Open()
cmd.Execute___()
End Using
You can think of it now as if you had run an sql statement more like this:
DECLARE #ClientID Int
DECLARE #DateFrom DateTime
DECLARE #DateTo DateTime
Set #ClientID = ImaginaryFunctionToGetQueryData('ClientID')
Set #DateFrom = ImaginaryFunctionToGetQueryData('DateFrom')
Set #DateTo = ImaginaryFunctionToGetQueryData('DateTo')
SELECT ...
FROM ...
WHERE tblClient.ClientID= #ClientID
AND tblBackupArchive.BackupDate >= #DateFrom
AND tblBackupArchive.Backupdate < #DateTo
The "ImaginaryFunction" in that code is accomplished using the sp_executesql stored procedure, but the point is that the query string as seen by sql server will never substitute data directly into the query string. Code is code, data is data, and never the 'twain shall meet.
Just as an addition to Joel's answer....
I'd avoid using any strings in the equation at all.
IE; Don't use textboxes to store the dates, use proper calendar or datetimepickers.
This way, you won't have to do this;
cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = DateTime.Parse(txtDateFrom.Text)
as Joel suggests, but instead you can just do;
cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = dtDateFrom.value
This way your not reliant on the DateTime.parse actually picking the correct format from your string. And you'll only be using date types.