Date/Time as string in Access SQL - Select a specific date - sql

I would like run a SQL in MS Access like the following:
SELECT Time, Ask, Bid
FROM AUDCAD
WHERE Time LIKE '2016.10.05'
ORDER BY ID;
However the result is nothing, The Time field data is look like the following:
2016.12.05 09:42:17.026
2016.12.05 09:42:17.387
2016.12.05 09:42:17.951
2016.12.05 09:42:18.464
...
2016.12.06 09:24:41.449
2016.12.06 09:24:41.854
2016.12.06 09:24:42.258
Therefore, I would like to extract the data day by day (this example: 2016.10.05)
Can anyone help me to solve this problem?
Lawrence

You need to check two things first...
Did your insert query work without errors .. are you sure time '2016.10.5' data exist in your DB?
Can you execute standard query to get time data and it works? Meaning can you 'SELECT FROM AUDCAD" ang get time data 2016.10.5

You must use the proper syntax for date expressions in Access SQL:
SELECT [Time], Ask, Bid
FROM AUDCAD
WHERE [Time] = #2016/10/05#
ORDER BY ID;
or, if Time has a time component:
SELECT [Time], Ask, Bid
FROM AUDCAD
WHERE Fix([Time]) = #2016/10/05#
ORDER BY ID;
However, it looks like you retrieve data from a DateTime2 field in SQL Server.
Thus, either change the data type to DateTime, or use the SQL Native Driver version 10 or 11 for your ODBC connection. If not, you will receive the date/time as text, not date/time values.

The separator for DateTime fields is #. Ex: #12/30/2016#.
I would recommend to always use the american order in VBA (m/d/y) even if the local machine is configured otherwise. It works fine that way.

Your sample query
SELECT Time, Ask, Bid
FROM AUDCAD
WHERE Time LIKE '2016.10.05'
ORDER BY ID;
uses a LIKE clause without any wildcards, so WHERE Time LIKE '2016.10.05' behaves just the same as WHERE Time = '2016.10.05'. That won't return any rows because the [Time] column always includes some characters after the date.
By default, Access uses the asterisk (*) as the "0 or more characters" wildcard, so
SELECT Time, Ask, Bid
FROM AUDCAD
WHERE Time LIKE '2016.10.05 *'
ORDER BY ID;
should work. Alternatively, you could use the ALIKE ("ANSI LIKE") keyword with the percent (%) wildcard:
SELECT Time, Ask, Bid
FROM AUDCAD
WHERE Time ALIKE '2016.10.05 %'
ORDER BY ID;

Related

Sorting SQL Query by Numbers as String

I am working on creating some reports from data that someone else created the databases for and am having trouble getting proper sorts.
This report is supposed to show the 20 most recent entries, but the data does not include a timestamp, instead it was created using two separate varchar fields, one for the date in the format MM/dd/yyyy and one for the time in the format HH:mm:ss AM/PM. This is causing issues when I try to select the most recent data.
When I use:
SELECT top 20 * FROM SignIn order by Checkin desc, Intime desc
I get the correct date, but the times are the values that start with 9:59am and go down from there alphabetically with 6am immediately after 7pm.
After doing much research I tried, among other things:
SELECT * FROM SignIn order by Checkout desc, CONVERT(varchar(30), outtime, 101) desc
The results were the same.
I don't do much in MS SQL, I am more fluent with with MySql and have never seen any reason to have dates stored as straight strings before. I am at a loss as to getting it to sort correctly.
I have tried creating the report with the html, php, and javascript handling the sort and display instead of having SQL just access the first records, but the load time is ridiculous since it loads the full 5000 pieces of data and then sorts them and clips all but the first 20.
As much as I wish I could, I can't change the database storage at this time, so I need something that will work with the varchars and handle the am\pm distinction if at all possible.
Any help would be appreciated.
You can concatenate the two columns and cast the result as datetime and use it for sorting.
SELECT top 20 *
FROM SignIn
ORDER BY cast(Checkout+' '+outtime as datetime) desc
Note that this assumes all the dates and times are valid. In case you may have incorrect values, use try_cast (for SQL Server versions 2012 and later)
SELECT top 20 *
FROM SignIn
WHERE try_cast(Checkout+' '+outtime as datetime) is not null --invalid values get filtered out
ORDER BY cast(Checkout+' '+outtime as datetime) desc
Just you have to concatenate your date time columns and convert to date like the following:
SELECT * FROM SignIn order by CONVERT(DATETIME, [dateColumn] + ' ' + [TimeColumn], 101) desc
you can learn more about datetime format in this tutorials link

convert SQL string into a date that can be queried

I am pulling from a database using the following:
SELECT
ID, CUSTOMER, NAME, etc, etc, TERM_INDEX
FROM "DAB055.ADT" DAB055
Now I want to limit the date range we pull, so would like to do something like:
WHERE TERM_INDEX >= '01.01.2015'
but the output in that field looks like:
20150629W
How can I convert that into a usual date field within the same statement, so that it can be filtered on?
Thanks.
It looks like your dates are stored in a format that will sort chronologically by using the alphabetical order. You can probably just say WHERE TERM_INDEX >= '20150101'.
Also it shouldn't be difficult to grab the first 8 characters and convert to a date type. Without knowing which platform you're on we'd have to guess at the syntax though.
One of these might work to figure out what your database server is:
select ##version
select * from v$version

Strange behaviour of Sql query with between operator

There is this strange error in sql query.
The query is something like this.
select * from student where dob between '20150820' and '20150828'
But in the database the column of dob is varchar(14) and is in yyyyMMddhhmmss format,Say my data in the row is (20150827142545).If i fire the above query it should not retrive any rows as i have mentioned yyyyMMdd format in the query.But it retrives the row with yesterday date (i.e 20150827112535) and it cannot get the records with today's date (i.e 20150828144532)
Why is this happening??
Thanks for the help in advance
You can try like this:
select * from student
where convert(date,LEFT(dob,8)) between
convert(date'20150820') and convert(date,'20150828'))
Also as others have commented you need to store your date as Date instead of varchar to avoid such problems in future.
As already mentioned you would need to use the correct date type to have between behave properly.
select *
from student
where convert(date,LEFT(dob,8)) between '20150820' and '20150828'
Sidenote: You don't have to explicitly convert your two dates from text as this will be done implicitly as long as you use an unambiguous date representation, i.e. the ISO standard 'YYYYMMDD' or 'YYYY-MM-DD'. Of course if you're holding the values in variables then use date | datetime datatype
declare #startdate date
declare #enddate date
select *
from student
where convert(date,LEFT(dob,8)) between #startdate and #enddate
Sidenote 2: Performing the functions on your table dob column would prevent any indexes on that column from being used to their full potential in your execution plan and may result in slower execution, if you can, define the correct data type for the table dob column or use a persistent computed column or materialised view if your performance is a real issue.
Sidenote 3: If you need to maintain the time portion in your data i.e. date and time of birth, use the following to ensure all records are captured;
select *
from student
where
convert(date,LEFT(dob,8)) >= '20150820'
and convert(date,LEFT(dob,8)) < dateadd(d,1,'20150828')
All you have to do is to convert first the string to date.
select *
from student
where dob between convert(date, '20150820') and convert(date, '20150828')
Why is this happening?
The comparison is executed from left to right and the order of characters is determined by the codepage in use.
Sort Order
Sort order specifies the way that data values are sorted, affecting
the results of data comparison. The sorting of data is accomplished
through collations, and it can be optimized using indexes.
https://msdn.microsoft.com/en-us/library/ms143726.aspx
There are problems with between in T-SQL.
But if you want a fast answer convert to date first and use >= <= or even datediff to compare - maybe write a between function yourself if you want the easy use like between and no care about begin and start times ...
What do BETWEEN and the devil have in common?

Select data in date format

I have a query in which I want to select data from a column where the data is a date. The problem is that the data is a mix of text and dates.
This bit of SQL only returns the longest text field:
SELECT MAX(field_value)
Where the date does occur, it is always in the format xx/xx/xxxx
I'm trying to select the most recent date.
I'm using MS SQL.
Can anyone help?
Try this using ISDATE and CONVERT:
SELECT MAX(CONVERT(DateTime, MaybeDate))
FROM (
SELECT MaybeDate
FROM MyTable
WHERE ISDATE(MaybeDate) = 1) T
You could also use MAX(CAST(MaybeDate AS DateTime)). I got in the (maybe bad?) habit of using CONVERT years ago and have stuck with it.
To do this without a conversion error:
select max(case when isdate(col) = 1 then cast(col as date) end) -- or use convert()
from . . .
The SQL statement does not specify the order of operations. So, even including a where clause in a subquery will not guarantee that only dates get converted. In fact, the SQL Server optimizer is "smart" enough to do the conversion when the data is brought in and then do the filtering afterwards.
The only operation that guarantees sequencing of operations is the case statement, and there are even exceptions to that.
Another solution would be using PATINDEX in WHERE clause.
SELECT PATINDEX('[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]', field_value)
Problem with this approach is you really are not sure if something is date (e.g. 99/99/9999 is not date).
And problem with IS_DATE is it depends on configuration (e.g. DATEFORMAT).
So, use an appropriate option.

Does constructor DateTime take string or ONLY TIMESTAMP type as parameter?

I am working with SQLite SQL statement or Query.
So far, I was able to figure out some of things by asking stackoverflow question that can cause problem when executing such SQL Statement.
However, I still am not able to get any result?
Here is my SQL Query:
SELECT *
FROM Alarms
WHERE ALARMSTATE IN (0,1,2)
AND ALARMPRIORITY IN (0,1,2,3,4)
AND ALARMGROUP IN (0,1,2,3,4,5,6,7)
AND DateTime(ALARMTIME) BETWEEN datetime("2012-08-02 00:00:00")
AND datetime("2012-08-03 00:00:00")
ORDER BY ALARMTIME DESC
Here is my table as viewed within datagridView control:
As you can see, I have records from yesterdays and the day before in the table.
I corrected all the columns in question of their format such as my ALARMTIME, which is TEXT in data type. Still not getting any result, I decided to run the SQL statement right from within SQLite Administrator application as below. Surprisingly, I got the same result which is nothing or nill or null for dataset. However, SQLite Administrator showed me that DateTime accepts only TIMESTAMP as a parameter not TEXT. If so, my above SQL Statement won't work even if I have everything else correct. Am I correct in saying that?
Here is my answer. From what I understand, DATETIME supposed to take string or timestamp as a parameter, but in my case it doesn't work for me.
Since my column ALARMTIME is TEXT, I am able to query my table with the following SQL statement and retrieve dataset I am looking for.
SELECT *
FROM Alarms
WHERE ALARMSTATE IN (0,1,2)
AND ALARMPRIORITY IN (0,1,2,3,4)
AND ALARMGROUP IN (0,1,2,3,4,5,6,7)
AND ALARMTIME LIKE "2012/08/01%"
ORDER BY ALARMTIME DESC
I simply can't convert my ALARMTIME text into datetime type.
try using between 8/1 and 8/3 and you will get the ones for 8/2.
the way you have it should pull up the alarms in between the two times though
EDIT
can you change your ALARMTIME to a DATETIME format? Then you would be able to use the Between and you wouldn't have to convert the text to DATETIME.
if you Convert to DATETIME type you will have better flexibility in your query. it will be easier to use in the future as well.
I believe that DATETIME is a overloaded text type, so it should output text