Simple DateTime sql query - sql

How do I query DateTime database field within a certain range?
I am using SQL SERVER 2005
Error code below
SELECT *
FROM TABLENAME
WHERE DateTime >= 12/04/2011 12:00:00 AM
AND DateTime <= 25/05/2011 3:53:04 AM
Note that I need to get rows within a certain time range. Example, 10 mins time range.
Currently SQL return with Incorrect syntax near '12'."

You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'

You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
Sql Server string to date conversion

This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}

You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14

SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.

select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM

Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).

if you have a type of datetime and you want to check between dates only ,,,use cast to select between two dates ....
example...
... where cast( Datetime as date) >= cast( Datetime as date) AND cast( Datetime as date) <= cast( Datetime as date)

Related

Change a datetime2 column to date

I'm trying to convert a column in SQL Server Express from a datetime2(7) format to a date format.
I have tried convert, a number of different ways with brackets and parenthesis but I'm having issues either with 'binding' or syntax.
dbo.stateByStatehood.annexDate
USE bigCity
--1.
SELECT CONVERT(datetime2(7), GETDATE()) annexDate;
--2.
SELECT CONVERT (datetime2(7)), stateByStatehood.annexDate date
You can go for cast to date datatype as given below:
SELECT CONVERT(date, GETDATE()) as annexDate;
SELECT CAST(GETDATE() AS DATE) as annexDate
annexDate
2021-08-27

Converting string 'yyyy-mm-dd' to date

I want to select from table where date column is equal to specific date which I sending as a string in format 'yyyy-mm-dd'. I need to convert that string and than to compare if I have that date in my table.
For now I am doing this:
select *
FROM table
where CONVERT(char(10), date_column,126) = convert(char(10), '2016-10-28', 126)
date_column is a date type in table and I need to get it from table in this format 'yyyy-mm-dd' and because that I use 126 format. I am just not sure with the other part where I converting string which is already in that format and do I need to convert it because I don't know is it good to use this:
CONVERT(varchar(10), date_column,126) = '2016-10-28'
You don't need to convert the column as well. In fact, you better not convert the column, because using functions on columns prevents sql server from using any indexes that might help the query plan on that column.
Also, you are converting a string to char(10) - better just convert it to date:
where date_column = convert(date, '2016-10-28', 126)
Also, if you are using a datetime data type and not date, you need to check that the datetime value is between the date you pass to the next date.
You can convert string to date as follows using the CONVERT() function by giving a specific format of the input parameter
declare #date date
set #date = CONVERT(date, '2016-10-28', 126)
select #date
You can find the possible format parameter values for SQL Convert date function here
You do not need to do that. yyyy-MM-dd is the default format.
Please note that you need to take into account the time as well, if there's a timestamp in date_column. In that case you should write something like this
... WHERE date_column >= '2016-10-28 00:00:00' AND date_column < '2016-10-29 00:00:00'
... WHERE date_column BETWEEN '2016-10-28 00:00:00' and '2016-10-29 00:00:00'
As I just learned that (other than I thought) BETWEEN actually includes the end timestamp and thus is not equivalent to the above >= ... < approach.
This should use indexes properly as well.

How to convert datetime to date without using convert function in sql server

I'm trying to convert datetime to date using convert function. But it is taking large as there is huge data in the table.
Is there any other way to do this without using convert function in less time.
Query:
Select *
from address
where convert(date,record-created_date) between '6/29/2016' and '6/30/2016'
You can simply remove CONVERT function as following query, so no time is spent for converting, but instead you have to add time to your [record-created_date] column in the WHERE clause:
SELECT *
FROM [address]
WHERE [record-created_date] BETWEEN '6/29/2016 00:00:00:000' AND '6/30/2016 23:59:59:999'
With SQL 2008 you can use CAST:
select cast(record-created_date as date)
In older versions, you can use DATEADD/DATEDIFF:
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, record-created_date))
You can define 2 constants in advanced, thus avoid using convert function on the column:
declare #min_date datetime
declare #max_date datetime
set #min_date = convert(datetime, '06/29/2016', 101)
-- Max date needs to be the next date of your end date
set #max_date = convert(datetime, '06/30/2016', 101) + 1
Select *
from address
where record-created_date >= #min_date
and record-created_date < #max_date
Just omit the conversion and add one day to the end date:
where record_created_date between '6/29/2016' and '7/1/2016'
This is interpreted as <= '7/1/2016 0:00', so use this short form only if is okay that midnight of the following day is included. Otherwise use the long form:
where record_created_date >= '6/29/2016' and record_created_date < '7/1/2016'
...or add the time:
where record_created_date between '6/29/2016' and '6/30/2016 23:59:59.999'
Btw., I think it is better to use the date format '2016-06-29' for hardcoded dates.
Anyway the main reason for being slow is most likely a missing index for this column.

How to filter only the date from a string stored in a varchar

Ii have values stored in the SQL Server in the following manner : 02-Jul-12 12:00:00 AM here the time and minutes, seconds can be anything like 02-Jul-12 12:15:52 PM ,02-Jul-12 6:02:12 AM so on.
I want to have a where condition which will omit the time and take the data based on the date like the following where some_Date='02-Jul-12'
How would I do this?
SELECT * FROM whatever WHERE some_Date LIKE '02-Jul-12%';
If you are on SQL2008 or later, you can cast your DATETIME to DATE.
See this post: http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
But in a WHERE-clause it is better to search between dates, like this:
DECLARE #startDate DATETIME = '02-Jul-2012'
DECLARE #endDate DATETIME = DATEADD(DAY, 1, #startDate)
SELECT * FROM [table] WHERE [some_Date] BETWEEN #startDate AND #endDate
SELECT * FROM dbo.tbl_MyTable
WHERE
REPLACE(CONVERT(VARCHAR(9), DateTimeValueColumn, 6), ' ', '-')='02-Jul-12'
or
On chage in code is instead of using getdate function voncert you datestring in datetime format and do compare this follow query will work for you
SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) =
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
If you are storing dates as characters -- which is not recommended -- you should at least use ISO format: YYYY-MM-DD hh:mm:ss. This makes the date useful for sorting and comparisons ("<" works, ">" works, "between" works as well as equals).
To extract the date, you can then use left(datestr, 10). In your format, you would use:
where left(datestr, 9) = '01-Jan-13'
If you are storing the fields as a datetime or smalldatetime, you may think they are stored as a string. They are not. They are stored as some number of days since some particular date, with day parts stored as fractional days. If you are using SQL Server 2005 or greater, then the best way is:
where cast(datetime as date) = '2013-01-01' -- I recommend ISO formats, even for constants. '20130101' is even better
To select rows with today's date (not time)
select * from myTable where datediff(dd, dateColumn, getdate()) = 0

SQL: retrieve records between dates in all databases

I would like to select all the records in a table between two dates. I have a query like:
SELECT * FROM <table> WHERE (thedate BETWEEN DATE('2012-04-01') AND DATE('2012-06-30'))
This is fine for HSQL, Oracle, PostgreSQL, but it doesn't work in SQL Server due to the lack of the Date function. Is there a way to get this to work generally for all databases (including SQL Server) or do I need to use an ORM like Hibernate (I know I should, but I'm specifically asking if this can be done in SQL)?
There's no need for the Date(...) as far as i can tell. This example seems to work
DECLARE #TheDate Date = '2012-07-01';
SELECT 'hello' WHERE (#TheDate BETWEEN '2012-04-01' AND '2012-06-30')
--None returned
SET #TheDate = '2012-05-01'
SELECT 'hello' WHERE (#TheDate BETWEEN '2012-04-01' AND '2012-06-30')
--selects hello
Edit Btw worth looking at This Question with the date time answer (will post here just to save effort)
The between statement can cause issues with range boundaries for dates as
BETWEEN '01/01/2009' AND '01/31/2009'
is really interpreted as
BETWEEN '01/01/2009 00:00:00' AND '01/31/2009 00:00:00'
so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:
myDate >= '01/01/2009 00:00:00' AND myDate < '02/01/2009 00:00:00' --CORRECT!
or
BETWEEN '01/01/2009 00:00:00' AND '01/31/2009 23:59:59' --WRONG! (see update!)
UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 01/01/2009 23:59:59.997!!
For this reason, the BETWEEN (firstday) AND (lastday 23:59:59) approach is not recommended.
Use the myDate >= (firstday) AND myDate < (Lastday+1) approach instead.
in sql-server I think you may want to look into the
DATEADD ( datepart , number, date )
DATEDIFF ( datepart , startdate , enddate )
but I think you're looking for
CAST ( expression AS data_type )
or
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
usage:
Select * from myTable where thedateToCompare >= CONVERT ( datetime , "dd/mm/yy hh:mi:ss:mmmAM" ) and thedateToCompare <= CONVERT ( datetime , "dd/mm/yy hh:mi:ss:mmmAM" )
something that may change your approach is weather your source 'thedate' column type datetime, smalldatetime or is it stored in a column defined as string?
You may want to check out a link! for more detial on datetime constants that you could use for your string variations.