Search
Active

11
Sign in to vote
2
Sign in to vote
Sign in
to vote
Type: Suggestion
ID: 483913
Opened: 8/19/2009 1:18:41 PM
Access Restriction: Public
3
Workaround(s)
There are a lot of different schools of thought on how to best trim the time from a date, or get the first day of the month, or the first day of the year, etc. For trimming the time, you can use DATEDIFF(), or CONVERT to CHAR(8) with style 112, or convert to FLOAT, etc. For first day of the month and year there are funky DATEADD/DATEDIFF/DATEPART tricks that nobody in their right mind can memorize.

While in SQL Server 2008 we have the DATE data type, which makes trimming time easy...

DECLARE @d DATETIME;
SET @d = CONVERT(DATE, CURRENT_TIMESTAMP);
SELECT @d;

...even those of us who have upgraded have not already changed all of our data types (this can be a huge refactoring effort) and we still have to potentially pull DATETIME/SMALLDATETIME data from linked servers, so we can't just change everything to DATE and forget about time components.

And besides, it doesn't solve the other little intricacies of rounding to specific dates. For example, Oracle has a function called TRUNC() which by default trims the time but can also accept parameters like 'MONTH' which will return the first day of the month. You can see documentation on Oracle's TRUNC() function here:

http://www.techonthenet.com/oracle/functions/trunc_date.php
Details (expand)
Product Language
English

Category

SQL Engine
Proposed Solution
Add a function called DATEROUND(UNIT, DATE/DATETIME/SMALLDATETIME value) where UNIT is one of:

DECLARE @d SMALLDATETIME = '2009-08-19 17:32';

DATEROUND(DAY, @d) returns '2009-08-19'
DATEROUND(YEAR, @d) returns '2009-01-01'
DATEROUND(MONTH, @d) returns '2009-08-01'
DATEROUND(QUARTER, @d) returns '2009-07-01' *
DATEROUND(WEEK, @d) returns '2009-08-16' **

* quarter is always a tricky one, and is often best solved by calendar tables anyway, but for standard fiscal year this could work as QUARTER is currently implemented in DATEADD, DATEDIFF etc.

** though this would depend on DATEFIRST settings, just like DATEPART(WEEKDAY,...) does.

Perhaps the value could be optional, and instead would use CURRENT_TIMESTAMP by default. So if today is 2009-08-19, this:

SELECT DATEROUND(DAY);

Would yield:

2009-08-19
Benefits
Faster Development
Other (please provides details below)
Other Benefits
Less Bing'ing for those complex formulae that get first day of month etc.
File Attachments
0 attachments
Sign in to post a comment.
Posted by AaronBertrand on 8/22/2009 at 11:26 PM
One thing I forgot to mention, obviously it would be okay (and in a lot of cases preferable) if the return type of DATEROUND() is DATE. Which I guess precipitates the need for a corresponding TIMEROUND() function, sorry. :-)
Posted by Microsoft on 9/9/2009 at 8:01 PM
Hi Aaron,

Thank you for the suggestion, we will keep this in mind for future versions of SQL Server.

- Tobias