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
Related
I have a Time column in which is in minute , in ssrs i need to get average and output in such a way that its in Day, Hour and min.
For example Column name is Time (Min).How to write an expression in such a way that we can get result in day, hour and min
Assuming that your time column is just an integer datatype containing a number of minutes then something like this will work.
The following calculates based on a report parameter to make it easier to test so oyu will need to swap this out for the correct column name and aggregations. e.g. if you time column is called MyTime and you want to calculate based on the average then swap out Parameters!MyMins.Value with AVG(Fields!MyTime.Value)
= INT(Parameters!MyMins.Value / 1440) & " days " &
INT((Parameters!MyMins.Value MOD 1440) / 60) & " hours " &
(Parameters!MyMins.Value MOD 60) & " mins"
adjust the output to suit you formatting requirements....
The above turns 4455 minutes into the string "3 days 2 hours 15 mins"
Enter the following expression:
=Format(TimeSerial(0,Parameters!MyMins.Value,0),"dd") & " Days "
& Format(TimeSerial(0,Parameters!MyMins.Value,0),"HH") & " Hours "
& Format(TimeSerial(0,Parameters!MyMins.Value,0),"mm") & " Minutes "
Alternatively, create another parameter e.g. MyTime
=TimeSerial(0,Parameters!MyMins.Value,0)
(Ensure that this parameter is evaluated after MyMins by moving it down the list)
Then put that into the code above
=Format(Parameters!MyTime.Value,"dd") & " Days "
& Format(Parameters!MyTime.Value,"HH") & " Hours "
& Format(Parameters!MyTime.Value,"mm") & " Minutes "
I am having abit of a situation and hope you can point me at the right direction.
1st DSUM (Text2):
=DSum("[quantity_ya7]","Stock","[part_number]= '" & [part_number] & "'")
2nd DSUM (Text2): (This can be Null at times as there are no withdrawals or records)
=DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' ")
After setting the 2 DSUM above, I will carry the subtract out.
=Text1-Text2
If there are values for to calculate for 2nd DSUM, the result will display in order. Else, it will be empty. (No values displayed)
How do I calculate as -0 (deduct 0) so I can get the right value displayed?
Thank you, much appreciated.
You can use the Nz function to return zero, a zero-length string ("
"), or another specified value when a Variant is Null. For example,
you can use this function to convert a Null value to another value and
prevent it from propagating through an expression.
https://support.office.com/en-gb/article/Nz-Function-8ef85549-cc9c-438b-860a-7fd9f4c69b6c
In your case you want the DSUM to return 0 rather than Null when there's no value so you can use it in a calculation.
=NZ(DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' "),0)
I am trying to use the query below to insert a concatenated converted set of integers to string for use on a datetime field in my table.
TABLE
Field Type
empID int(11)
time_stamp datetime
in_out char(3)
am_pm char(2)
QUERY
Dim query As String = "INSERT INTO attendance VALUES(" & empID.Text & _
"STR_TO_DATE(CONCAT("& empYear.Text & ",'-'," & empMonth.Text & ",'-'," & _
empDay.Text & ",' '," & empHour.Text & ",':'," & empMin.Text & ",':'," & _
empSec.Text & ",'%Y-%m-%d %H:%i:%s'),'out','pm')"
There is no problem with the connection and the values. I have tried to insert the values into a test column of string type and the output is this:
133201712311827
I am pretty sure it's with how I use these characters: '' "" "," - :. I just can't figure out how.
First problem I see, here
& empID.Text & "STR_TO_DATE(. . . .
you're missing comma after first value
& empID.Text & "***,*** STR_TO_DATE(. . . .
Second issue, I identified when I've replaced your text values with hard coded values - You are missing closing parenthesis for str_to_date. Here ,'%Y-%m-%d... should be ), '%Y-%m-%d...
STR_TO_DATE(CONCAT(1999,'-',01,'-',01,' ',10,':',25,':',30***)***,'%Y-%m-%d %H:%i:%s')
As you see- my replacement shows that you have no issues with concatenation, single quote and :. Theo only other variable here is quality of data in text boxes.
Update
This answer (above) is correct. Using sql fiddle I created schema and when replaced text box values with hard-coded ones - all worked. My suggestions to add comma and parenthesis hold true. Your claim about problems with single quotes are false.
create table xxx (empID int(11), time_stamp datetime, in_out char(3), am_pm char(2));
INSERT INTO xxx VALUES(123,
STR_TO_DATE(CONCAT('2017','-','1','-','23',' ','10',':','35',':','40'),'%Y-%m-%d %H:%i:%s'),
'out','pm');
commit;
Select * from xxx
empID | time_stamp | in_out | am_pm
123 | January, 23 2017 10:35:40 | out | pm
End Update
On top of that, you could do it much better by parameterizing, which will look like something like this
command.CommandText = "insert into ... values (#1, #2, #3, #4)"
command.Parameters.AddWithValue("#1", Convert.ToInt32(empID.Text))
dim date as new DateTime(Convert.ToInt32(empYear.Text), Convert.ToInt32(empMonth.Text), . . . . )
command.Parameters.AddWithValue("#2", date)
. . . . . .
command.ExecuteNonQuery()
Parameterizing will make it easy to work with dates and strings
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
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 + "'"