mysql: searching BETWEEN dates stored as varchar - sql

i would like to select * from table where dates between (some_date and another_date)
the problem is that the dates are stored as varchar!
here are examples of dates that i have:
7/29/2010 9:53 AM
7/16/2010 7:57:39 AM
please notice that some records have seconds and some do not
i dont care about the time at all i just need the date
reporttime is the date field
this is not working:
SELECT * FROM batchinfo
where cast(reporttime as date) between ('7/28/10' and '7/29/10')
this:
SELECT * from batchinfo WHERE reporttime BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y %h:%i:%s %p')
AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y %h:%i:%s %p')
is returning:
Truncated incorrect datetime value: '7/8/2010 11:47 AM'
Incorrect datetime value: '0.00012009' for function str_to_date
this:
SELECT * from batchinfo WHERE STR_TO_DATE(reporttime, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y')
AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y')
is returning:
Incorrect datetime value: '7/8/2010 11:47 AM' for function str_to_date
OMG PONIES:
i am taking everything before the first blank:
SELECT * from batchinfo WHERE STR_TO_DATE(LEFT(reporttime,LOCATE(' ',reporttime)), '%m/%/d/%Y') BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y')
AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y')
and now i get this returned:
Incorrect datetime value: '7/8/2010' for function str_to_date

You want to search between dates, store them as dates. By storing them as strings you're shooting yourself in the foot.
You'd basically need to extract date part from the string (using SUBSTR() or LEFT() ) and parse it to date format (using STR_TO_DATE()).
The performance of such solution will be appaling.
STR_TO_DATE(LEFT(reporttime,LOCATE(' ',reporttime)),'%m/%d/%Y') BETWEEN '2010-07-28' AND '2010-07-29'

Use STR_TO_DATE to convert the strings to the DateTime data type. The format shorthand is found under DATE_FORMAT:
STR_TO_DATE(column, '%m/%/d/%Y %h:%i:%s %p')
The problem is, you'll have to update the VARCHAR dates to all be the same format first, before you can use:
WHERE STR_TO_DATE(reporttime, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE(some_date, '%m/%/d/%Y')
AND STR_TO_DATE(another_date, '%m/%/d/%Y')
Date formats are not consistent (some use hyphens, others slashes and Year/Month/day order can be totally different...), so STR_TO_DATE is the most accommodating & consistent means of turning a string into a DateTime. Only after the value is DateTime, does Date/Time functionality become available like DATE() to get only the date portion...
Because of the data type change, an index on some_date & another_date columns can not be used.

IF you are using SQl use this query
Data
DECLARE #Dates TABLE (StartDate varchar(100));
INSERT INTO #Dates VALUES ('7/1/2010 9:10 AM');
INSERT INTO #Dates VALUES ('7/5/2010 10:33 AM');
INSERT INTO #Dates VALUES ('7/13/2010 04:53 AM');
INSERT INTO #Dates VALUES ('7/22/2010 8:45 AM');
INSERT INTO #Dates VALUES ('7/10/2010 11:20 AM');
INSERT INTO #Dates VALUES ('7/11/2010 12:40 AM');
Query:
SELECT * FROM #Dates
WHERE (CONVERT(datetime,StartDate,101) >= CONVERT(datetime,'7/1/2010 9:10 AM',101))
AND (CONVERT(datetime,StartDate,101) <= CONVERT(datetime,'7/15/2010 9:10 AM',101))
ORDER BY CONVERT(datetime,StartDate,101)

You can CAST your varchar values to DATETIME or DATE type.
WHERE CAST(dates AS DATE) BETWEEN (7/28/10 and 7/29/10)
This might not be an optimal solution, because you may lose the benefit that indexes provide.

This Date query will work perfectly...
Database 'Date' Will be like '01/01/2016' and datatype is 'varchar'
SELECT * FROM `test` WHERE STR_TO_DATE(`test`.`date`, '%d/%m/%Y') BETWEEN '2016-01-01' AND '2016-01-31' ORDER BY `test`.`date` ASC

If date is in Varchar
Query
AND c.sentdate > '2016-jun-15'

Related

SQL Server convert varchar hh:mm:ss to time

Is there a way to convert varchar 'hh:mm:ss' format data to time to allowing summing?
DECLARE #InX VARCHAR(10)='09:08:23'
SELECT CAST(#InX AS TIME(0))
You can convert those values to time and for summing you could simply get their difference in seconds from midnight and sum. Result would be in seconds. ie:
DECLARE #times TABLE(t TIME(0));
INSERT INTO #times(t)VALUES('03:20:30'), ('02:10'), ('01:00');
SELECT SUM(DATEDIFF(SECOND, '00:00:00', t))FROM #times AS t;

How to cast varchar to datetime in sql

I need to cast a string to a datetime so i can compare it later.
The varchar that i have is like this format:
29/11/2013 12:00:00 a.m.
And i need it to cast to:
2013-11-29 00:00:00.000
Im using MSSQL Server 2012
Thx for all
Please, have a look a CAST and CONVERT for more information.
Here are some examples:
-- converting from DD-MM-YYYY
select CONVERT(datetime, '29/11/2013 12:00:00 AM', 103)
-- converting from MM-DD-YYYY
select CONVERT(datetime, '11/29/2013 12:00:00 AM', 101)
IF Your date is of type varchar in the database then if you need to retrieve
then these cases arises::
case1:if your data is in the format of "dd-MM-yyyy"
then you need to use query as follows
Query::
select * from [yourTableName] where convert(datetime,YourDateColumn,103) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'
case2:if your data is in the format of "dd-MM-yyyy HH:mm:ss"
then you need to use query as follows
Query::
select * from [yourTableName] where convert(datetime,YourDateColumn,105) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'

SQL Server CE date stored in string : how to compare

I have a database in which, I see that dates are stored in the form of strings. Would it be possible for me to compare those date (in the form of string ) in a query?
For eg. column date1 stores 09-11-1992 00:00:00 and date2 stores 22-11-1992 00:00:00
Would it be sensible to execute a query as follows:
select * from tablename WHERE date1 > "06-11-1992 00:00:00";
If your strings are in a recognizable format, you should be able to cast them to datetimes and compare.
select *
from tablename
where cast(date1 as datetime) > cast('06-11-1992 00:00:00' as datetime)
However, I'd recommend ISO 8601 format for dates. Here's one possibility:
cast('1992-11-06T00:00:00' as datetime)
I'm assuming DD-MM-YYYY here because of your date2 example.
Just be sure you know which is the day and which is the month. Hopefully your strings are always the same format and are in-line with your regional settings.
Be careful: you may have to set the date format to get the right output from your data:
set dateformat dmy
select cast('06-11-1992 00:00:00' as datetime) -- returns 1992-11-06 00:00:00
set dateformat mdy
select cast('06-11-1992 00:00:00' as datetime) -- returns 1992-06-11 00:00:00

How to assign current date with specific time to column?

How do i assign current date with a specific time?
let's say 8:00:00 AM to Column EXIT_DT of datatype datetime??
I have tried GETDATE() AS EXIT_DT but it gives me current datetime. I am using Sql server 2005. Any help?
Lets say Today is 1/3/2013 and i want my result to return as a datetime datatype with value 1/3/2013 8:00:00 AM. If i run the statement ytd, the result will be 1/2/2013 8:00:00 AM
This formula will always produce 08:00 for the day it is called, and avoids string manipulation:
select DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00')
Try to avoid solutions that convert to and from strings - treating datetime values as strings is one of the largest sources of bugs.
It works by computing the number of days (as an integer) that have elapsed since 1st January 2001. It then adds that same number of days to 08:00 on 1st January 2001.
You can try this :
DECLARE #dt datetime;
SET #dt=CONVERT(DateTime, CONVERT(VARCHAR,GETDATE(),101)+' 8:00:00')
SELECT CONVERT(VARCHAR, #dt, 101)+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20),#dt, 100), 7))
Visit http://www.sql-server-helper.com/tips/date-formats.aspx for datetime formats.
Use Convert along with getdate() to get specific formats.
ex:
SELECT CONVERT(VARCHAR(30),GETDATE(),113)
This is a bit stupid, but it works
select cast(cast(getdate() as date) as datetime) + '08:00:00'
it casts the getdate() to date thus losing the hours, than it casts it to datetime and adds 8 hours.
If you want to avoid implicit conversion of varchar to datetime, you could use this version:
select cast(cast(getdate() as date) as datetime)
+ convert(datetime,'08:00:00',114)
This is also working. (1). convert today's date to ISO format (yyyymmdd) (2). add the time, (3). convert back to datetime
Select convert(datetime, convert(varchar, getdate(),112) + ' ' + '8:00:00AM')
--Results
2013-01-03 08:00:00.000
If you need in specific format you need to convert back to varchar again.
-- AM/PM --
SELECT TO_CHAR(sysdate, 'MM/DD/YYYY HH:MI:SS AM') FROM dual
/
-- 24 hrs format --
SELECT TO_CHAR(sysdate, 'MM/DD/YYYY HH24:MI:SS') FROM dual
/

sql server: what's wrong with my date data?

i have a column with dates, but it is a varchar:
8/31/2010 9:48
8/31/2010 9:49
8/31/2010 9:51
8/31/2010 9:52
8/31/2010 9:55
8/31/2010 9:59
8/31/2010 10:11
8/31/2010 10:13
8/31/2010 10:16
8/31/2010 10:37
8/31/2010 10:42
i made sure that none of these will be a BAD date:
SELECT *
FROM qcvalues.dbo.batchinfo
WHERE ISDATE(reporttime) <> 1
this returned 0 results
question:
i need to return dates between a certain range:
select rowid from qcvalues.dbo.batchinfo where CONVERT(DATE, Substring( reporttime, 1, LEN(reporttime)), 103)
between cast('2010-08-01' as datetime) and CAST('2010-08-31' as datetime)
and i am getting this error;
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
what is wrong with my conversion?
If you need to store dates then use a datetime column in the future
does this work?
WHERE CONVERT(DATE,RTRIM(reporttime))
BETWEEN '2010-08-01' and '2010-08-31'
If not use SET DATEFORMAT MDY before running it
And if you have to store it in a varchar column then use YYYYMMDD format...that way you can do
WHERE reporttime like '201008%' if you want August 2010
This will solve your problem:
select rowid
from qcvalues.dbo.batchinfo
where
CONVERT(DATE, reporttime, 101) >= '20100801'
-- style 101, not 103
-- also notice date conversion invariant format YYYYMMDD with no separators
AND CONVERT(DATE, reporttime, 101) < '20100901'
-- using BETWEEN with an end date of '8/31/2010' will skip
-- times between '8/31/2010 00:00:00.003' and '8/31/2010 23:59:59.997'
Try this to see what the problem is:
select convert(datetime, '8/31/2010 9:48', 103)
select convert(datetime, '8/31/2010 9:48', 101)
put SET DATEFORMAT MDY before your query.
This will strip out the time portion too
select rowid
from qcvalues.dbo.batchinfo
Where cast(floor(cast(cast(reportTime as datetime)as float))as datetime)
between cast('2010-08-01' as datetime)
and cast('2010-08-31' as datetime)
Remember, this CAST('2010-08-31' as datetime) will have its time portion as 00:00.
Consider casting your varchar data as smalldatetime, and being specific about the boundaries of times in your between. No need to be converting, substring, etc. Just one CAST will do.
Consider this as a potential solution:
SELECT rowid from qcvalues.dbo.batchinfo
WHERE CAST(reporttime as smalldatetime)
BETWEEN '2010-08-01' AND '2010-08-31 23:59'