The scenario is this:
select max date from some table, when the target table having no data, so the max date is null. when the date being null, I want to get the earliest date of system, so the epoch time seems perfect.
I have searched some ways including DATEADD functions, but that seems not elegant.
If I understand your question correctly, in SQL Server the epoch is given by cast(0 as datetime) :
select Max(ISNULL(MyDateCol, cast(0 as datetime)))
from someTable
group by SomeCol
The earliest date that can be stored in a SQL datetime field depends on the data type you use:
datetime:
1753-01-01 through 9999-12-31
smalldatetime:
1900-01-01 through 2079-06-06
date, datetime2 and datetimeoffset:
0001-01-01 through 9999-12-31
For more exact details see from https://msdn.microsoft.com/en-GB/library/ms186724.aspx#DateandTimeDataTypes
The epoch is useful if you are converting numbers to dates, but irrelevant if you are storing dates as dates.
If you don't want to deal with nulls properly the simple answer is to pick a date that you know will be before your data and hard-code it into your query. cast('1900-01-01' as datetime) will work in most cases.
While using something like cast(0 as datetime) produces the same result it obscures what you have done in your code. Someone maintaining it, wondering where these odd old dates come from, will be able to spot the hard coded date more quickly.
If you define the epoch as Jan 1, 1970: The better: to store it in a variable
DECLARE #epoch DATETIME
SET #epoch = CONVERT( DATETIME, '01 JAN 1970', 106 )
select
DATEPART(YEAR, DATEADD(day, 180, #epoch)) as year,
...
Related
I got my answer from Martin on how to convert epoch to date time but now I am facing another issue. How to do I filter records that are only entered today or some other date?
I created view with DATEADD(SECOND, Timing, '19700101') and want to filter out records.
select * from [dbo].[vw_records]
where Timing like '%23-10-2019%'
This way I am not able to query datetime based on that view. So as far the conversion it is good solution but for querying records not too good.
On other hand, maybe it is better to convert it in the table and then query results. hm...
Any suggestions please..
If you want rows from today, then use inclusive Date logic:
SELECT {Columns list}
FROM YourTable
WHERE DateColumn >= CONVERT(date, GETDATE())
AND DATECOLUMN < DATEADD(DAY, 1, CONVERT(date, GETDATE()));
For today, this'll return all rows on or after 2019-10-28T00:00:00:00.000 and before (but not including) 2019-10-29T00:00:00:00.000.
I want to query a datetime field using a range of dates provided in the format DD/MM/YYYY.
I know that to convert datetime to a DD/MM/YYYY format that I can use:
CONVERT(CARCHAR(10), ORDERDATE,103)`
And this works fine when querying a single date, eg:
SELECT DISTINCT
CONVERT(DATE, ORDERDATE),
CONVERT(CARCHAR(10), ORDERDATE,103)
FROM ORDERS
WHERE CONVERT(CARCHAR(10), ORDERDATE,103) = '19/10/2017'
Returns: 2017-10-19, 19/10/2017
However it does not work on a range of dates, eg:
WHERE CONVERT(CARCHAR(10), ORDERDATE,103) BETWEEN '17/10/2017' AND '19/10/2017'
Returns:
2014-02-05
2016-12-12
2013-04-30
I know there are hundreds of threads about SQL dates, but they all seem to be regarding reformatting the output and not preparing the input. Do I need to reformat my DD/MM/YYYY inputs?
To query a range of dates, use the DATE-datatype instead of VARCHAR.
If datatype of column ORDERDATE is DATETIME:
WHERE CONVERT(DATE, ORDERDATE) BETWEEN
CONVERT(DATE, '17/10/2017', 103) AND CONVERT(DATE, '19/10/2017', 103)
The conversion of ORDERDATE is only necessary if the start and end date are the same. (in this case, when no conversion is done, only dates with a time value of '00:00:00.000' will be returned)
EDIT:
To omit the conversion of ORDERDATE you can add the time to the dates and convert them to DATETIME instead of DATE, like this:
WHERE ORDERDATE BETWEEN
CONVERT(DATETIME, '19/10/2017 00:00:00') AND CONVERT(DATETIME, '19/10/2017 23:59:59.999');
Or even simpler, like suggested in #Used_By_Already's answer:
WHERE ORDERDATE >= '20171017' AND ORDERDATE < '20171020' --Note the end date is here +1 day
SQL Server date information should NOT be stored "in a format". If if they are literally stored in that format then they are NOT dates as far as the database is concerned (they are "strings" that look like dates) and you will have a nightmare to deal with if they are DD/MM/YYYY because they simply will not behave like dates should.
There are several specific data types in SQL Server for date/time information (datetime, datetime2, smalldatetime, date, time) but ALL of these do not store data in a human readable format at all. Instead they stored as groups of numbers, which will be displayed in a human readable manner, and in your case - by default - you are seeing then in DD/MM/YYYY format. A user in China might prefer to see a date in YYYY.MM.DD or in the USA as MM/DD/YYYY. This is possible because a human format is applied on top of the numbers that are stored before they get displayed.
So. In SQL Server there is a "safe" date literal in the form of 'YYYYMMDD' and this may be used without the need to CONVERT or CAST:
IF your [ORDERDATE] column is a date (or smalldatetime/datetime/datetime2) then this will work:
WHERE ORDERDATE BETWEEN '20171017' AND '20171019'
OR, you may explicitly convert a string to but you need a "style number" to be present to make these fully reliable. Style 103 for example is for DD/MM/YYYY
WHERE ORDERDATE BETWEEN CONVERT(date, '17/10/2017',103) AND CONVERT(date, '19/10/2017',103)
Although "between" has been used in the discussion above a far more reliable method of forming date ranges is to NOT use "between", instead do it this way:
WHERE ORDERDATE >= '20171017' AND ORDERDATE < '20171020'
With this pattern (note the second day is now +1) it does not matter which date precision is stored in the column. For example, see Bad habits to kick : mis-handling date / range queries
I have a DateTime column called “Date_Entered” and I need to filter between two dates and within these two dates to filter between two times (time might be of the next day). Here is my query:
Declare #StartDate DateTime
Declare #EndDate DateTime
Declare #StartTime varchar(8)
Declare #EndTime varchar(8)
SELECT Date_Entered FROM MyTable
WHERE (Date_Entered BETWEEN '1/1/2014' AND '1/1/2015')
AND (CONVERT(varchar(8), Date_Entered, 108) >= '21:00:00' OR #StartTime IS NULL)
AND (CONVERT(varchar(8), Date_Entered, 108) <= '03:00:00' OR #EndTime IS NULL) --This time value is on the next day to cover a 6-hour period
The desired results should display all values that are within the date range (for 2014 year) and took place during the 6-hour range (night time):
2014-05-15 21:09:00
2014-08-12 02:45:00
2014-09-05 01:40:00
All the above happened during a date range (2014) and between the time of 9PM and 3AM on the next day.
My problem is that I need to search for time that happens from 9PM and 3AM on the next day (for the same date range)
If I search for time range in the same day like from 21:00 to 23:59 I get the results, but when time goes over the next day then I won't get any result.
Any idea how to do that in SQL.
SSRS 2012 is used to enter the value for the parameters.
The Date_Entered field is DateTime type that has date and a time.
If i understood your question correctly then the below code will give correct output
create table a
(enddate datetime
)
insert into a values ('2014-05-15 21:09:00')
insert into a values ('2014-08-12 02:45:00')
insert into a values ('2014-09-05 01:40:00')
Query
SELECT enddate FROM a
WHERE (enddate BETWEEN '1/1/2014' AND '1/1/2015')
AND (CONVERT(varchar(8), enddate, 108) >= '21:00:00' )
or (CONVERT(varchar(8), enddate, 108) <= '03:00:00' )
Result
May, 15 2014 21:09:00
August, 12 2014 02:45:00
September, 05 2014 01:40:00
Is it possible for you to convert the separate date and time fields into a single datetime field? Here's a link to a relevant SO question that provides an option for you to convert your search criteria into a single field. By doing so, it should let you to search for times beyond midnight within a single query.
SQL Server convert string to datetime
I have seen many examples on the internet regarding similar issues, but nothing quite what I am trying to achieve.
My Scenario
I have a table which stores an EndTime in minutes (1050) meaning 17:30:00
I have written a query to update a column in a referenced table when its null, however the date itself is set to 1900-01-01 17:30:00.000. And no matter what I try, I only get the date correct or time correct... heres the query that converts the int to time and displays the incorrect date above:
UPDATE t
SET t.EndTime = (
SELECT CONVERT (datetime, DATEADD(MINUTE, EndTime, '00:00:00'), 108)
FROM Staff
WHERE
StaffID = t.StaffID
)
FROM TimesheetLine t
WHERE t.EndTime IS NULL
I am trying to achieve 2015-01-07 17:30:00.000
Staff.EndTime is where the 1050 minutes are stored
TimesheetLine.EndTime is the field I am trying to set to 2015-01-07 17:30:00.000 when it is null
thankyou for your help and apologies if there is a duplicate question...
If you just want to take a date and add 17:30:00 on to it you can do something like this:
SELECT DATEADD(MINUTE, 1050, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))
So it takes a given date, in this instance I've used GETDATE() to get the current date. I've converted it to a date and then back to a datetime to strip off the time portion. Then used DATEADD() to add on the specified number of minutes.
Output:
2015-07-01 17:30:00.000
So if I read your query right you would do this:
UPDATE t
SET t.EndTime = (
SELECT DATEADD(MINUTE, EndTime, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))
FROM Staff
WHERE StaffID = t.StaffID
)
FROM TimesheetLine t
WHERE t.EndTime IS NULL
I am trying to add days to the current date and it's working fine but when I add 360 days to the current date it gives me wrong value.
eg: Current Date is 11/04/2014
And I am adding 360 Days to it, it should give me 11/04/2015, but it is showing the same date 11/04/2014. the year is not changing.
Here is my code:
select dateadd(dd,360,getdate())
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
select dateadd(dd,360,getdate()) will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
Two or three ways (depends what you want), say we are at Current Date is
(in tsql code) -
DECLARE #myCurrentDate datetime = '11Apr2014 10:02:25 AM'
(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)
SELECT #myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.
SELECT DateADD(DAY, 365, #myCurrentDate) or DateADD(dd, 365, #myCurrentDate)
will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE #myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).
So what I think you meant was
SELECT DateADD(year, 1, #myCurrentDate)
which gives 2015-04-11 10:02:25.000.
or better yet
SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, #myCurrentDate), 0))
which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?
This will give total number of days including today in the current month.
select day(getDate())
Add Days in Date in SQL
DECLARE #NEWDOB DATE=null
SET #NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query