How to find field with date range? - sql

So I'm trying to select record with a specific date range ex. 5/21/2019 - 5/30/2019 and put the records into a datagridview.
I'm using Ms. Access and I don't know many things about SQL.
DA = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= " & DateValue(FirstDate) & " AND date <= " & DateValue(SecondDate) & "", conn)
DS = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")
It doesn't give me an error message, but the datagridview doesn't show anything. Thanks for your response

In MS Access, the date delimiter is a hash (#).
So have to change your query to:
"SELECT * FROM table where date >= #" & DateValue(FirstDate) & "# AND date <= #" & DateValue(SecondDate) & "#"
Or you use the between operator:
"Select * FROM table WHERE [Date] Between #" & DateValue(FirstDate) & "# and #" & DateValue(SecondDate) & "#";

A better way to handle this is to simply use parameters which is commonly recommended by many programmers.
da = New OleDb.OleDbDataAdapter("SELECT * FROM table where date >= #StartDate AND date <= #EndeDate ", conn)
'If you show how you declare and set FirstDate and SecondDate we can drop the DateValue function'
da.SelectCommand.Parameters.Add("#StartDate", OleDb.OleDbType.Date).Value = DateValue(FirstDate)
da.SelectCommand.Parameters.Add("#EndeDate", OleDb.OleDbType.Date).Value = DateValue(SecondDate)
ds = New DataSet
DS.Clear()
DA.Fill(DS, "table")
DataGridView1.DataSource = DS.Tables("table")

SELECT ID
FROMTestInfo
WHERE CapturedDate BETWEEN ‘2012-03-27’ AND ‘2012-03-28 ’

Related

SQL filter Date from Label in VB.net

I am stuck with little problem. I have a sql database with DATE column. It is populated from a Label like this: Label1.text = Date.today
and need to show records from one date in datagridwiev. So I need filter date using date from Label. So far I have this:
Public Sub ShowData()
cmd = New SqlCommand("Select * FROM Cisnik WHERE Datum = #" & Label3.Text & "# ", con)
If con.State = ConnectionState.Closed Then con.Open()
myDA = New SqlDataAdapter(cmd)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "Cisnik")
DGV3.DataSource = myDataSet.Tables("Cisnik").DefaultView
End Sub
This code throws : Incorrect syntax near '11.'. The number 11 is a part of European form of date 24.12.2018
The database works OK. Only need this filter problem to solve.
Try:
cmd = New SqlCommand("Select * FROM Cisnik WHERE Datum = '" & cdate(label3.Text).ToString("yyyy-MM-dd") & "'", con)
Your query will be:
Select * FROM Cisnik WHERE Datum = '2018-11-11'
(date example)

SQL Between Date Range query working for some tables, but not others

I've got 6 database tables storing information on commission rates and which rate to use depending on the customer/supplier/product and order date.
Using these tables, I have a procedure to calculate the amount of commission due to the user. This works fine for the first stages of the order, as it uses the current date, so my SQL is along the lines of
Dim p1Dt As New DataTable
Dim pDa As New OleDbDataAdapter("SELECT * FROM [Promotional Rates] WHERE Supp_Code=? AND " & _
"Product_Code=? AND Rate_Start_One <= DATE() AND " & _
"Rate_End_One >= DATE()", con)
pDa.SelectCommand.Parameters.Add("#supplier", OleDbType.VarChar).Value = cmbSupplier.Text
pDa.SelectCommand.Parameters.Add("#product", OleDbType.VarChar).Value = ugr.Cells("Product_Code").Value
pDa.Fill(p1Dt)
However, when the order has been delivered, the commission is then re-calculated with the delivery date for the product, which is taken from the database.
My code for doing this is a little bit different, since it isn't calculating it with the current date. Instead, I'm using this code
Dim deliveryDate As Date
deliveryDate = ugr.Cells("Final_Delivery").Value
Dim p1Dt As New DataTable
Dim pDa As New OleDbDataAdapter("SELECT * FROM [Promotional Rates] WHERE Supp_Code=? " & _
"AND Product_Code=? AND Rate_Start_One <= #" & _
deliveryDate & "# AND Rate_End_One >= #" & _
deliveryDate & "#", con)
pDa.SelectCommand.Parameters.Add("#supplier", OleDbType.VarChar).Value = cmbSupplier.Text
pDa.SelectCommand.Parameters.Add("#product", OleDbType.VarChar).Value = ugr.Cells("Product_Code").Value
pDa.Fill(p1Dt)
If I save the Final_Delivery value as 11/03/2017 (11th March), the deliveryDate value is being assigned as 11/03/2017.
I have a rate in the Promotional Rates table for all of March, so I'm expecting the above query to have 1 row in the table, however, it's returning 0, so is using the wrong values for the commission.
This doesn't happen when I use the DATE() method, it finds all of the rows in the tables correctly, so the issue lies somewhere in the way I'm entering dates in the second method.
Why would the second method not find the row in the database when I'm writing the query in this format?
EDIT
This is the full CommandText, after hovering over the OleDbDataAdapter variable and copy and pasting the CommandText
"SELECT * FROM [Promotional Rates] WHERE Supp_Code=? AND Product_Code=? AND Rate_Start_One " & _
"<= #11/03/2017# AND Rate_End_One >= #11/03/2017#"
The data in the database, to prove that it's got the correct dates in:
Sales Lines (For the Final_Delivery value)
Promotional Rates (For the date range)
The answer was, as #Plutonix mentioned, along with a couple of other people in a different forum - Using parameters to pass the dates in.
I completely forgot that this was even possible, in truth, but the way around the issue is parameterising the queries, such as:
Dim deliveryDate As Date = ugr.Cells("Final_Delivery").Value
Dim p1Dt As New DataTable
Dim pDa As New OleDbDataAdapter("SELECT * FROM [Promotional Rates] WHERE Supp_Code=? AND " & _
"Product_Code=? AND Rate_Start_One <= ? AND Rate_End_One " & _
">= ?", con)
pDa.SelectCommand.Parameters.Add("#supplier", OleDbType.VarChar).Value = cmbSupplier.Text
pDa.SelectCommand.Parameters.Add("#product", OleDbType.VarChar).Value = ugr.Cells("Product_Code").Value
pDa.SelectCommand.Parameters.Add("#dFrom", OleDbType.Date).Value = deliveryDate
pDa.SelectCommand.Parameters.Add("#dTo", OleDbType.Date).Value = deliveryDate
pDa.Fill(p1Dt)
Access interprets dates in SQL strings as mm/dd/yyyy no matter what your regional settings are. Have a read up here http://allenbrowne.com/ser-36.html for some methods of dealing with it.
In the query designer this doesn't apply - which is very confusing. And it interprets Date() correctly no matter where you use it.
Your SQL should read:
"SELECT * FROM [Promotional Rates] WHERE Supp_Code=? AND Product_Code=? AND Rate_Start_One " & _
"<= #2017/03/11# AND Rate_End_One >= #2017/03/11#"
so modify like this:
Dim pDa As New OleDbDataAdapter("SELECT * FROM [Promotional Rates] WHERE Supp_Code=? " & _
"AND Product_Code=? AND Rate_Start_One <= #" & _
deliveryDate.ToString("yyyy'/'MM'/'dd") & "# AND Rate_End_One >= #" & _
deliveryDate.ToString("yyyy'/'MM'/'dd") & "#", con)

VB.NET Database Query to Chart a Quantity Vs Date

I have a table in an Access database with information like the following:
DATE SERIAL RESULT
1/5/2016 5299 PASS
1/5/2016 5371 PASS
1/6/2016 5280 PASS
1/6/2016 3962 FAIL
1/7/2016 1325 PASS
I'm trying to run a query to display a count of the SERIAL's that have a RESULT of "PASS" and plot them for each day. The closest I have managed to get is the following:
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim query As String
Dim FullDatabasePath As String = "C:\db.accdb"
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbSource As String = " Data Source = " & FullDatabasePath
Dim table As String = "tblQA"
query = "SELECT [DATE], (SELECT COUNT([SERIAL]) FROM " & table & " WHERE [DATE] BETWEEN #" & dtpFrom.Value.ToString("MM/dd/yyyy") & "# And #" & dtpTo.Value.ToString("MM/dd/yyyy") & "# AND RESULT = 'PASS') as RowCount FROM [" & table & "] WHERE DATE BETWEEN #" & dtpFrom.Value.ToString("MM/dd/yyyy") & "# And #" & dtpTo.Value.ToString("MM/dd/yyyy") & "# AND RESULT = 'PASS'"
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection
con.ConnectionString = dbProvider & dbSource
da = New OleDb.OleDbDataAdapter(query, con)
ds.Clear()
con.Open()
da.Fill(ds, table)
con.Close()
Chart1.Series.Add("PASS")
Chart1.DataSource = ds.Tables(table)
Chart1.Series("PASS").XValueMember = "DATE"
Chart1.Series("PASS").YValueMembers = "RowCount"
If I select 1/5/2016 for both start and end dates using the DateTimePickers on my form (dtpFrom and dtpTo), my chart shows me 2 serials on 1/5/2016. Likewise, it shows 1 serial if I choose a start and end date of 1/6/2015. (yay)
If choosing a start date of 1/5/2016 and end date of 1/7/2016, it shows 4 serials on each of those 3 days. (boo)
How can I make it not accumulate, but instead display the number of passing serials for each day?
I believe this SQL will do what you want:
SELECT [DATE], COUNT(RESULT)
FROM Table_1
where result = 'PASS' AND [Date] BETWEEN '20160501' AND '20160701'
group by [date]
EDIT: The dates are formatted to suit MS T-SQL - you'll have to tweak these to suit Access ( and your dtp's) of course.

select records which will be ended after 2 days

I need to get the records that will be ended after two days
but always I got an empty datagridview.
I have tried this code:
Dim after2days As Date = Today.Date.AddDays(3)
Dim sqlstr As String = "SELECT * FROM tblvac where vend between " & Today.Date & " and " & after2days & " "
Dim da As New OleDbDataAdapter(sqlstr, Conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Conn.Close()
Why is this happening and how can I fix it?
Access SQL includes functions, Date() and DateAdd(), which can give you the date range you want for your query.
Dim sqlstr As String = "SELECT * FROM tblvac where vend between Date() and DateAdd('d', 3, Date());"
If you prefer to pass date values from your VB.Net code to the db engine, use a parameter query so that you needn't bother about date format and delimiters. Just supply valid Date/Time values for the parameters.
You are building your query as a string and thus need to use the convert to date function... for MS Access its DateValue see http://www.techonthenet.com/access/functions/date/datevalue.php
Try
Dim sqlstr As String = "SELECT * FROM tblvac where vend between
DateValue('" & Today.Date & "') and DateValue('" & after2days & "') "
As commented by HansUp... this solution needs to have the date format as mm/dd/yyyy or yyyy-mm-dd

Missing Operator Help VB

Syntax Error Missing Operator in query Expression 'doj>=#03/Jan/2016 and 'doj<=#03/Jan/2016'.
SQL = "select * from tbluser Where doj >=#" & DateTimePicker1.Text & " # and <=#" & DateTimePicker2.Text & "#"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.CommandType = CommandType.Text
acsdr = acscmd.ExecuteReader
If acsdr.Read = True Then
Label1.Text = (acsdr.GetValue(0).ToString())
End If
In this line
SQL = "... Where doj >=#" & DateTimePicker1.Text & " # and <=#" & DateTimePicker2.Text "#"
there isn't a doj field before the <=# part of your string and there is no & symbol to concatenate the last # to the previous string.
Said that, you should forget about this way to query a database.
The correct way is through parameters like here
SQL = "select * from tbluser Where doj >= #p1 and doj <= #p2"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.Parameters.Add("#p1", OleDbType.Date).Value = DateTimePicker1.Value.Date
acscmd.Parameters.Add("#p2", OleDbType.Date).Value = DateTimePicker2.Value.Date
acsdr = acscmd.ExecuteReader
.....
This query uses parameters, it is not subject to Sql Injection, the parameters are passed with the correct datatype expected by the columns involved in the query, there is no confusion caused by the concatenation in your command text.
EDIT
Following your comment below, if you want to know the number of rows that have a doj value between two dates then you should change your query and introduce the scalar function COUNT
SQL = "select COUNT(*) from tbluser Where doj >= #p1 and doj <= #p2"
acscmd = New OleDbCommand(SQL, acsconn)
acscmd.Parameters.Add("#p1", OleDbType.Date).Value = DateTimePicker1.Value.Date
acscmd.Parameters.Add("#p2", OleDbType.Date).Value = DateTimePicker2.Value.Date
Dim result as Integer = acscmd.ExecuteScalar
.....
The command executes the method ExecuteScalar instead of ExecuteReader because there is only the value calculated by the COUNT function to return and not whole records of data.