SQL query to retrieve data between two dates - mysql

I've written following code:
Dim date1 As Date
Dim date2 As Date
date1 = Convert.ToDateTime(DatePickerFromDate.Text)
date2 = Convert.ToDateTime(DatePickerToDate.Text)
Dim cnd As New OleDbCommand("SELECT * FROM Sales WHERE Invoice_Date BETWEEN " + date1 + " AND " + date2 + "", om)
om.Open()
Dim da As OleDbDataReader = cnd.ExecuteReader
While da.Read()
ComboBox1.Items.Add(da(0))
End While
da.Close()
om.Close()
I want to retrieve data between two dates that are been taken from two datepickers.
I tried BETWEEN, also i tried >= =< but result was empty though database contains data. Please help where I'm getting wrong

Your code is probably generating an error. When doing this type of querying, you should store the query string after substitution and print it out. You seem to be missing delimiters around the dates. So this may work in your specific case.
New OleDbCommand("SELECT * FROM Sales WHERE Invoice_Date BETWEEN '" + date1 + "' AND '" + date2 + "'", om)
However, you then need to be careful about the format of the dates. The application layer and the database might use different formats. If you are substituting directly into the query string, then use the format YYYY-MM-DD -- it is the ISO standard date format and generally understood.
Even better is to learn how to parameterize queries so you can actually pass in the date values as date parameters.

If you're using MS Access, this should be the syntax...
SELECT * FROM Sales WHERE Invoice_Date>=#" + date1 + "# and Invoice_Date<=#" + date2 + "#"
If you're using MS SQL Server or MySQL, then do something like this...
SELECT * FROM Sales WHERE Invoice_Date>='" + date1 + "' and Invoice_Date<='" + date2 + "'"

Related

Date coming back wrong from SQL

I have a date in my table that is in there as 2016-12-05 etc
When I use a select statement to get that value back however it comes back in a really odd way: Mon Dec 5 00:00:00 UTC 2016
How do I get this to come back in YYYY-MM-DD?
Edit:
Using JSCRIPT. Select command is
SELECT AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'"
BadgeNo being a variable defined above somewhere
Use DATE_FORMAT() function for this
In your case, it will be :
SELECT DATE_FORMAT(AccessDate, '%Y-%m-%d') as AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'"
refer this documentation
MySQL DATE_FOMAT() reference
Hope it helps.
I think this can help you.
for MySQL
DATE_FORMAT(STR_TO_DATE(myValue, '%d.%m.%y'), '%Y-%m-%d')
look for str_to_date : http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date
edit: for MSSQL
SELECT CONVERT(char(10), GetDate(),126)
why 126? look there: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Use this:
$Date_database= $row['date']; // your database code
$Date= date('Y-m-d', strtotime($Date_database)); // change to right date format
Date Contains 2016-12-05 now

Performing column operations in CASE WHEN statment condition in sql query

I'm developing an application using vb.net2008 with database as msaccess. I've designed a table in database having columns IN_TIME and OUT_TIME in format HH:MM:SS . I want a result as TOT_TIME which will display difference between these two columns. I've written a query for this, now i'm facing a problem that i dont want to display result if IN_TIME is less than 8:00:00 AM else display result. I have used CASE WHEN but it didnt worked, help me out.
I've tried this so far
SELECT *
(CASE WHEN LATE_LIMIT > '" + date3 + "'
THEN ROUND(([PM_OUT]-[OVERIME_LIMIT]),2)
ELSE 'N' )AS OverTime
FROM DTR_REC
You are missing a comma and an END case:
SELECT *
,(CASE WHEN LATE_LIMIT > '" + date3 + "'
THEN ROUND(([PM_OUT]-[OVERIME_LIMIT]),2)
ELSE 'N' END)AS OverTime
FROM DTR_REC
But I'm not sure if Access supports CASE statements. If not does this work:
SELECT *
,IIF(LATE_LIMIT > '" + date3 + "', ROUND(([PM_OUT]-[OVERIME_LIMIT]),2),'N') AS OverTime
FROM DTR_REC

SELECT Between dates almost working

My problem is likely all about date formatting in a SELECT.
In an asp file I open an ADO Recordset wanting to retrieve rows of a MS SQL table that fall between date1 (08/15/2013) and date2 (08/22/2013) (i.e., the previous 7 days from today's date.)
The SELECT does retrieve the appropriate 2013 rows but also retrieves rows going back to 08/15/2012.
Here is the SELECT:
oRS.Source = "SELECT * FROM aTable WHERE entry_Date BETWEEN '" & resultLowerDate & "' AND '" & resultCurrentDate & "' AND entry_Status <> 'INACTIVE'"
resultLowerDate = 08/15/2013 and resultCurrentDate = 08/22/2013.
The table is set up as follows with resultCurrentDate = "08/22/2013":
entry_Status entry_Date (varchar) LastName FirstName SELECT Result
INITIAL 08/15/2012 Smith Jim YES
INACTIVE 08/21/2012 Green Tom no
INITIAL 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Brown Sally yes
FOLLOWUP 08/22/2013 Smith Jim yes
Any thoughts as to why the INITIAL 08/15/2012 row gets selected along with the other rows that meet the SELECT query?
STOP STORING DATES IN VARCHAR COLUMNS! And STOP CONCATENATING STRINGS, USE PROPER PARAMETERS.
Sorry to yell, but we are getting multiple questions a day where people use the wrong data type for some unknown and probably silly reason, and these are the problems it leads to.
The problem here is that you are comparing strings. Try:
"... WHERE CONVERT(DATETIME, entry_date, 101)" & _
" >= CONVERT(DATETIME, '" & resultLowerDate & "', 101)" & _
" AND CONVERT(DATETIME, entry_date, 101)" & _
" < DATEADD(DAY, 1, CONVERT(DATETIME, '" & resultCurrentDate & "', 101))"
Or better yet, set resultLowerDate and resultUpperDate to YYYYMMDD format, then you can say:
"... WHERE CONVERT(DATETIME, entry_date, 101) >= '" & resultLowerDate & "'" & _
" AND CONVERT(DATETIME, entry_date, 101) < DATEADD(DAY, 1, '" & resultCurrentDate & "'"
Note that I use an open-ended range (>= and <) instead of BETWEEN, just in case some time slips into your VARCHAR column.
Also note that this query could fail because garbage got into your column. Which it can, because you chose the wrong data type. My real suggestion is to fix the table and use a DATE or DATETIME column.
The fact that your entry_Date column is a varchar field and not an actual date is the problem. If you cast it to a datetime during the select, you'll get the results you expect.
select *
from aTable
where cast(entry_Date as datetime) between '08/15/2013' and '08/22/2013'
Sql Fiddle link

MS Access Syntax error (missing operator)

I am using the below code to get the record from a access database. Now i got the below error Syntax error (missing operator) in query expression.
I can't able to understand this issue. Please help me to fix this issue.
cmd = new OleDbCommand(#"Select * from tbl_men_schedule where fld_mem_id=" + 0 + " and fld_startdate=" + Convert.ToDateTime(txt_startDate.Text) + " and fld_enddate=" + Convert.ToDateTime(txt_enddate.Text) + "", con);
da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Syntax error (missing operator) in query expression 'fld_mem_id=0 and fld_startdate=1/4/2013 12:00:00 AM and fld_enddate=4/11/2013 12:00:00 AM'.
If fld_startdate and fld_enddate are Date/Time data type, enclose those date values with the # delimiter.
where
fld_mem_id=0
and fld_startdate=#1/4/2013 12:00:00 AM#
and fld_enddate=#4/11/2013 12:00:00 AM#
If they are text data type, enclose them with quotes.
where
fld_mem_id=0
and fld_startdate='1/4/2013 12:00:00 AM'
and fld_enddate='4/11/2013 12:00:00 AM'
However if you use a parameter query instead, you wouldn't need to delimit those values.
Your statement should be -
"Select * from tbl_men_schedule where fld_mem_id=" + 0 + " and fld_startdate='" + Convert.ToDateTime(txt_startDate.Text) + "' and fld_enddate='" + Convert.ToDateTime(txt_enddate.Text) + "'"
Hope this helps you
If you hardcoding "0"... and you're missing single quotes.
"Select * from tbl_men_schedule where fld_mem_id=0 and fld_startdate='" +
txt_startDate.Text + "' and fld_enddate='" +
txt_enddate.Text + "'"

current_date casting

string selectSql = "update " + table + " set state_" + mode + "_id=1 WHERE stoping_" + mode + " < current_date;";
When I call current_date, it returns yyyy-MM-dd format, but I want to return dd.MM.yyyy format, how can I do that. please help. My program works fine when I am trying
string selectSql = "update " + table + " set state_" + mode + "_id=1 WHERE stoping_" + mode + " < '16.04.2010';";
The MySQL date format is YYYY-MM-DD, but using str_to_date() and date_format() you can change the date format.
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
In your case, try DATE_FORMAT(current_date, '%d.%M.%Y')
mysql has a function that return current date - curdate()
So, your query must be like
update table set state_mode_id=1 WHERE stoping_mode < curdate()
But you have 2 major faults (or even 3):
date field must have a format of YYYY-MM-DD, not anything else
such an update is senseless at all, because all such states being evaluated at select time
assembling table name at query time is a sign of very bad database design
YYYY-MM-DD is mySQL's native date format. I find it hard to believe that doing a comparison against a DD-MM-YYYY string works?
Anway, what you are looking for is DATE_FORMAT().
Use any function like this to return your format
function ChangeDateforShow($inputdate) {
if($inputdate>0) {
$date = substr($inputdate,8,2);
$month = substr($inputdate,5,2);
$year = substr($inputdate,0,4);
$show = $date.".".$month.".".$year;
return $show;
}
}
function ChangeDateforDB($inputdate) {
if($inputdate>0) {
$date = substr($inputdate,0,2);
$month = substr($inputdate,3,2);
$year = substr($inputdate,6,4);
$show = $year."-".$month."-".$date;
return $show;
}
}
Ok use this function in db itself like
selectSql = "update " + table + " set state_" + mode + "_id=1 WHERE stoping_" + mode + " < 'ChangeDateforDB(customDATE)';"
Or otherwise you will move for mysql date_format() only