I need to search between dates and times.
For example, between date: 30/02/2007, time: 10:32 and date: 21/06/2008, time: 14:19
What is the most simple query for this?
Thanks in advance.
you should look at the date time formats available in SQL Server: http://msdn.microsoft.com/en-us/library/ms187928.aspx
yyyy-mm-dd hh:mi is what you should use:
try:
SELECT
*
FROM Records
WHERE DateCreated>='2007-02-30 10:32' AND DateCreated<='2008-06-21 14:19'
in the above query the strings will be converted to datetime data type if DateCreated is a datetime column. and the query will work.
you can create local variables of datetime data type and use a query like:
DECLARE #StartDate datetime, #EndDate datetime
SELECT #StartDate='2007-02-30 10:32', #EndDate='2008-06-21 14:19'
SELECT
*
FROM Records
WHERE DateCreated>=#StartDate AND DateCreated<=#EndDate
I like using <, <=, >=, or > because it allows more flexibility than BETWEEN and forces you to think about including endpoints or not.
Another thing to consider is getting all data from a complete day:
DECLARE #StartDate datetime, #EndDate datetime
--set the days you want
SELECT #StartDate='2007-02-30 10:32', #EndDate='2008-06-21 14:19'
--remove the time
SELECT #StartDate=DATEADD(day,DATEDIFF(day,0,#StartDate),0), #EndDate=DATEADD(day,DATEDIFF(day,0,#EndDate),0)
--get everything on '2007-02-30' up to the end of the day on '2008-06-21'
SELECT
*
FROM Records
WHERE DateCreated>=#StartDate AND DateCreated<#EndDate+1
Try this:
SELECT
*
FROM
Records
WHERE
DateCreated BETWEEN #Date1 AND #Date2
Related
I have an SQL table containing fields with date and time with columns start and end as DateTime.
What I want is a query that will select the row where the current date and time is between the value of start and end fields plus the type is WE.
Example:
If current date and time is 2022-05-18 15:30:00, row number 39 should be displayed as a result.
So far, this is the code I came up with but it returns zero result:
select * from `examdates` where (NOW() between `start` and `end`) and `type`='WE'
I also tried some answers I found in this forum like
select * from `examdates` where NOW() >= `start` and NOW() <=`end` and `type`='WE'
but result is still
Thanks!
Test this:
SELECT *
FROM `examdates`
WHERE CONVERT_TZ(NOW(), ##time_zone, '+00:00') BETWEEN `start` AND `end`
and `type`='WE'
The function retrieves server timezone info from session variable and converts the server local datetime to GMT time zone. If the values in the table are ones of some another timesone then adjust 3rd function parameter accordingly.
See https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=b054129c8210336d70b6f0a4ecc50b5d
If I use this in my dataset SQL:
DECLARE #StartDate DATE = '2018-01-01'
DECLARE #EndDate DATE = '2018-03-01'
The report runs and returns the expected Data.
When I comment out the #StartDate & #EndDate variables - delete the two parameters from the Report - and run the report using Date Prompts at run time [using the same Dates] - I get no data returned.
The Date field that I am attempting to filter on is a Datetime field.
I have tried the following two approaches in my SQL:
o.ORDERDATE >= #StartDate And o.ORDERDATE <= #EndDate
cast(o.ORDERDATE as DATE) >= Cast(#StartDate As Date) And cast(o.ORDERDATE as DATE) <= Cast(#EndDate As Date)
No data.
I added a Text Box to the Report Header and put the #StartDate Parameter value in there and got this: 01/01/2018 12:00:00 AM at run time.
I have gone back and forth a few times between uncommenting and commenting the Date variables at the top of the SQL. When I use the local variables - I get data. When I use the Date Parameters - no data.
I use Date Prompts in many of my other reports with no problems. I will go back and see if any of them is on this particular table and this particular date field - or if any of the other dates are Datetime fields ....
Meanwhile, I would appreciate any suggestions.
Thanks!
I would suspect a conversion issue comparing Date and DateTime types. To prove this, set the dates manually in your query to the full date and time. if this produces no results then try something simple like.
WHERE CAST(o.ORDERDATE AS Date) Between #StartDate AND #EndDate
Bear in mind that if you start your date with the year (I think) by default this is interpreted as being in YYYY-MM-DD format.
I have a column of bigint type containing date & time information (like 1353056515, 1353067040, 1360839600 etc.)
My requirement is to get time difference in HOURS format between column which I mentioned above and current datetime.
I tried to find the solution, but those were so confusing. I'm new to SQL Server.
Please help.
Please try this.
declare #mydate datetime
DECLARE #LocalTimeOffset BIGINT
,#AdjustedLocalDatetime BIGINT
SET #LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET #AdjustedLocalDatetime = 1416474000 - #LocalTimeOffset
SELECT DATEADD(second,#AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime))
-- It will give you date 2014-11-20 14:30:00.000
The data difference operation:
select DATEDIFF(hour,#mydate,GETDATE())
or
Create Function
create FUNCTION dbo.fn_ConvertToDateTime (#Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE #mydate datetime
DECLARE #LocalTimeOffset BIGINT
,#AdjustedLocalDatetime BIGINT
SET #LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET #AdjustedLocalDatetime = #Datetime - #LocalTimeOffset
SELECT #mydate=DATEADD(second,#AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime))
return #mydate
END;
GO
select mydate= dbo.fn_ConvertToDateTime (1416474000)
select DATEDIFF(hour,#mydate,GETDATE())
Hope that helps.
The number looks like a UNIX timestamp, which is the number of seconds since 1/1/1970 00:00:00 UTC. You can get the UNIX timestamp from a datetime with a simple DATEDIFF:
declare #date datetime='2014-11-20T10:00:00'
declare #epoch datetime='19700101'
select DATEDIFF(s,#epoch,#date)
To get the number of hours between two timestamps you simply need to divide the difference by 3600 (the number of seconds in an hour). You don't need to convert the timestamps to dates before calculating the difference :
declare #dateTS int=DATEDIFF(s,#epoch,#date)
declare #nowTS int=DATEDIFF(s,#epoch,GETUTCDATE())
select (#nowTS-#dateTS)/3600.0
Note that I used 3600.0 to get a decimal result. If 3600 is used the fractional part will be truncated and you'll get 0 for differences less than 1 hour. This is OK if you want to return whole hours.
In a query you could write something like this:
select (DATEDIFF(s,#epoch,GETUTCDATE())-[MY_TS_COLUMN])/3600.0 AS Hours
from [MY_TABLE]
This seems like overkill but is the only way I have been able to floor todays datetime to 00:00:00.000 at database level:
select CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)
I have tried using:
select FLOOR(getdate())
But get the following message:
Implicit conversion from data type datetime to float is not allowed. Use the CONVERT function to run this query.
Can anyone recommend another way of doing this?
Since you are using SQL Server 2008 you could make use of the date data type.
declare #Today date
set #Today = getdate()
select #Today
Or without the variable.
select cast(getdate() as date)
If you need to have the value as a datetime just cast it back to a datetime.
select cast(cast(getdate() as date) as datetime)
There are a lot of ways of doing this i have seen the floor one before. Here are a few more.
select cast(cast(CURRENT_TIMESTAMP as date) as datetime)
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SELECT CAST(CAST(CURRENT_TIMESTAMP - 0.50000004 AS int) AS datetime)
I normaly do the Cast to date version.
I need to filter all dates which greater than, say 01 january 2011.
select * from table_name where date > '01/01/2011';
the problem is that date field store int values, here is an example:
1339011098
1336717439
1339010538
How to convert the date field on the sql query (from the int format to date format), I need to convert it to a valid date so that I can compare it towards the above date.
Thanx.
You're going the wrong direction. Rather than converting potentially millions of records for the compare, try converting your target date, which you only need to do once. Those look like unix timestamps, so the resulting query should look like this:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('01/01/2011')
Or, if you can control this, try using the ISO date format, which avoids confusion with european date formats for dates like 3/2/13:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('2011-01-01')
You can use UNIX_TIMESTAMP()
select *
from table_name
where date > unix_timestamp('2011-01-01')
Or conversely use FROM_UNIXTIME()
select *
from table_name
where FROM_UNIXTIME(date, "%Y-%m-%d") > '2011-01-01'
First, you should not store date values as integers and if it's under your control your goal should be to fix the database and any queries that insert an integer value for that column instead of date.
The two date functions that you need to use with the current setup are UNIX_TIMESTAMP(), which accepts a date value and returns the epoch timestamp integer and FROM_UNIXTIME() which accepts an epoch timestamp integer and returns a date value.
For your example, you could use either:
SELECT * FROM table_name WHERE FROM_UNIXTIME(date_field) > '01/01/2011';
or
SELECT * FROM table_name WHERE date_field > UNIX_TIMESTAMP('01/01/2011');
But I would advise using FROM_UNIXTIME as a general rule as this would simplify more sophisticated queries such as:
SELECT * FROM table_name WHERE
FROM_UNIXTIME(date_field)
BETWEEN '01/01/2013' AND '04/01/2013';
Essentially, until your date field is actually storing values that are date types, your queries should covert the field values with FROM_UNIXTIME.