Av rating:
Total votes: 120
Total comments: 55


Robyn Page
Robyn Page's SQL Server DATE/TIME Workbench
16 August 2006
 
/*

Using dates, and times in SQL Server: a workbench approach

This "workbench" on use of dates and times in SQL Server is structured so it can be pasted in its entirity into the Query Analyser, SSMS or other GUI and the individual examples executed.

I'd like to encourage you to experiment. One never fails to come up with surprises; for example, I'd never, before writing this, considered using 'LIKE' when searching DateTime fields, or using the { t '2:40'} in a stored procedure as a literal date.

Likewise, I always like to see as many examples as possible in any articles on SQL Server. There is nothing like it for getting ideas going. Formal descriptions are fine for those with strange lumps in their brains, but I'd prefer to see clear explanations peppered with examples!

If I have any general advice, it is to use the strengths of the DATETIME data type and never attempt to bypass its use, by storing dates or times in any other formats. I've never come across a circumstance where such a practice has provided any lasting benefit.

Contents


Inputting dates
---------------


A user enters a date into form and you need to get it into a DATETIME data type
in The Database. Dates can be assigned to DateTime variables or columns as strings
but these are done according to the dateformat stored for the particular language
that is current. The orderin which the month (m), day (d), and year (y) is written
is different in other countries. US_English (mdy) is different from british (dmy).
By explicitly setting the date format you can over-ride this.


You can check your current DateFormat, amongst other things by using... */

 

DBCC USEROPTIONS


--now, to demonstrate that getting this wrong can cause unexpected errors.....

 

SET language british
SELECT CAST('14/2/2006' AS datetime) --2006-02-14 00:00:00.000
SET language us_english --Changed language setting to us_english.
SELECT CAST('14/2/2006' AS datetime) --**ERROR!***
--keep speaking American, but use the european date format
SET dateformat 'dmy' --to override the language default
SELECT CAST('14/2/2006' AS datetime) --2006-02-14 00:00:00.000
SET language british
SELECT CAST('14/2/2006' AS datetime) --2006-02-14 00:00:00.000
SET language us_english --Changed language setting to us_english.
SELECT CAST('14/2/2006' AS datetime) --2006-02-14 00:00:00.000

 

/* Any date representation based on words (e.g. febbraio, fevereiro, february)
will fail in any other language that uses a different word for a given month.
To see the current language settings, use: */

 

sp_HelpLanguage


/* To import foregn-language dates, you must change the language setting for the
connection.
e.g
*/
SET language Italiano SELECT CAST('10 febbraio 2006' AS datetime)
--Changed language setting to Italiano.
--2006-02-10 00:00:00.000




 

/* Otherwise SQL Server is fairly
accomodating, and will do its best to make sense of a date.*/


--all of the following return 2006-02-01 00:00:00.000





SET language british
SELECT CAST('1 feb 2006' AS datetime)--remember, this is language dependent
SELECT CAST('1 february 2006' AS datetime)--this too
SELECT CAST('01-02-06' AS datetime)
SELECT CAST('2006-02-01 00:00:00.000' AS datetime)
SELECT CAST('1/2/06' AS datetime)
SELECT CAST('1.2.06' AS datetime)
SELECT CAST('20060201' AS datetime)
--in SQL Server 2000 and 2005 you can specify dates in ISO 8601 format
SELECT CAST('2006-02-01T00:00:00' AS datetime)
SELECT CAST('2006-02-01T00:00:00.000' AS datetime)
--and you'll be able to enter in this format whatever the settings!

/* the ANSI standard date uses braces, the marker 'd' to designate the date,
and a date string */
SELECT { d '2006-02-01' }
/* the ANSI standard datetime uses 'ts' instead of 'd' and adds hours, minutes,
and seconds to the date (using a 24-hour clock) */
SELECT { ts '2006-02-01 00:00:00' }
/* 

If you use the CONVERT function, you can override the dateformat by choosing 
the correct CONVERT style (103 is the British/French format of dd/mm/yyyy 
(see later for a list of all the styles)                
*/
SET language us_english
SELECT CONVERT(DateTime,'25/2/2006',103)        --works fine
--whereas the 100 style uses the default supplied by the dateformat.
SELECT CONVERT(DateTime,'25/2/2006',100)        --error!
/*






The IsDate function
-------------------


The IsDate(expression) function is used for checking strings to see if they
are valid dates. It is language-dependent.



ISDATE (Expression) returns 1 if the expression is a valid date (according
to the language and dateformat mask) and 0 if it isn't

The following demonstration uses ISDATE to test out the input of strings as
dates. */
--
SET
LANGUAGE british SET nocount ON


--
DECLARE
@DateAsString VARCHAR(20),
@DateAsDateTime DateTime
SELECT @DateAsString='2 february 2002'
SELECT [input]=@DateAsString
IF (ISDATE(@DateAsString)=1)
BEGIN
SELECT
@DateAsDateTime=@DateAsString
SELECT [the Date]=COALESCE(CONVERT(CHAR(17),@DateAsDateTime,113),'unrecognised')
END
ELSE
SELECT
[the Date] ='That was not a date'

/*

Inputting Times
---------------


Times can be input into SQL Server just as easily. There are no separate time
and date types for storing only times or only dates. It is not necessary. If
only a time is specified when setting a datetime, the date is assumed to be
the first of january 1900, the year of the start of the new millenium.

If only a date is specified, the time defaults to Midnight.


e.g.
*/
SELECT CAST ('17:45' AS datetime) -- 1900-01-01 17:45:00.000
SELECT CAST ('13:20:25:850' AS datetime) -- 1900-01-01 13:20:25.850
SELECT CAST ('14:30:20.9' AS datetime) -- 1900-01-01 14:30:20.900
SELECT CAST ('3am' AS datetime) -- 1900-01-01 03:00:00.000
SELECT CAST ('10 PM' AS datetime) -- 1900-01-01 22:00:00.000
SELECT CAST ('02:50:20:500AM' AS datetime) -- 1900-01-01 02:50:20.500
SELECT CONVERT (DateTime,'02:50:20',108-- 1900-01-01 02:50:20.000

--  And times can be converted back from the DATETIME into the ascii VARCHAR
--  version as follows...
SELECT CONVERT(VARCHAR(20),GETDATE(),108) -- 15:08:52
--108 is the hh:mm:ss CONVERT style (See next section for the complete list)
SELECT LTRIM(RIGHT(CONVERT(CHAR(19),GETDATE(),100),7))-- 3:10PM
SELECT LTRIM(RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)) -- 3:19:18:810PM
--  and so on

--  You can input times a different way (note that the brackets are curly
--  braces

SELECT { t '09:40:00' }
--  which unexpectedly gives 09.40 today, rather than 9:40 on the first of
--  january 1900! (as one might expect from the other time input examples)
--  this is valid in a stored procedure too
CREATE PROCEDURE #spExperiment AS
SELECT
{ t '09:40:00' }
GO
EXEC #spExperiment
/*


Outputting dates
----------------




Dates can be output as strings in a number of ways using the CONVERT function
and CONVERT styles These styles are numeric codes that correspond with the
most popular date formats. You get much more versatility with the CONVERT 
function than the CAST function.



The CONVERT styles override the setting of the DATEFORMAT but use the
current language setting where the date format uses the name of the month.

If you run the following code you will get a result that illustrates all the
built-in formats , using the current date and time


--------------------------------------------------------------*/
DECLARE @types TABLE(
       
[2 digit year] INT NULL,
       
[4 digit year] INT NOT NULL, 
       
name VARCHAR(40))
SET LANGUAGE british SET nocount ON
--Each select statement is followed by an example output string using the style
INSERT INTO @types 
       
SELECT NULL,100,'Default'--Oct 17 2006  9:29PM
INSERT INTO @types 
       
SELECT 1,101'USA'--10/17/06 or 10/17/2006
INSERT INTO @types 
       
SELECT 2,102'ANSI'--06.10.17 or 2006.10.17
INSERT INTO @types 
       
SELECT 3,103'British/French'--17/10/06 or 17/10/2006
INSERT INTO @types 
       
SELECT 4,104'German'--17.10.06 or 17.10.2006
INSERT INTO @types 
       
SELECT 5,105'Italian'--17-10-06 or 17-10-2006
INSERT INTO @types 
       
SELECT 6,106'dd mon yy'--17 Oct 06 or 17 Oct 2006 
INSERT INTO @types 
       
SELECT 7,107'Mon dd, yy'--Oct 17, 06 or Oct 17, 2006
INSERT INTO @types 
       
SELECT 8,108'hh:mm:ss' --21:29:45 or 21:29:45
INSERT INTO @types 
       
SELECT NULL,109'Default + milliseconds'--Oct 17 2006  9:29:45:500PM
INSERT INTO @types 
       
SELECT 10,110,'USA' --10-17-06 or 10-17-2006
INSERT INTO @types 
       
SELECT 11,111,'JAPAN'--06/10/17 or 2006/10/17
INSERT INTO @types 
       
SELECT 12,112,'ISO'--061017 or 20061017
INSERT INTO @types  --17 Oct 2006 21:29:45:500 
       
SELECT NULL,113,'Europe default(24h) + milliseconds'
INSERT INTO @types 
       
SELECT 14,114,'hh:mi:ss:mmm (24h)' --21:29:45:500 or 21:29:45:500
INSERT INTO @types 
       
SELECT NULL,120,'ODBC canonical (24h)'--2006-10-17 21:29:45
INSERT INTO @types  --2006-10-17 21:29:45.500 
       
SELECT NULL,121'ODBC canonical (24h)+ milliseconds'
INSERT INTO @types 
       
SELECT NULL,126'ISO8601'--2006-10-17T21:29:45.500
-- insert into @types 
--           Select null,127, 'ISO8601 with time zone' --SQL Server 2005 only!
INSERT INTO @types 
       
SELECT NULL,130'Hijri'--25 ????? 1427  9:33:21:340PM
INSERT INTO @types 
       
SELECT NULL,131'Hijri'--25/09/1427  9:29:45:500PM
SELECT [name],
[2 digit year]=COALESCE(CONVERT(VARCHAR(3),[2 digit year]),'-'),
[example]=CASE WHEN [2 digit year] IS NOT NULL
THEN CONVERT(VARCHAR(30),GETDATE(),[2 digit year])
ELSE '-' END,
[4 digit year]=COALESCE(CONVERT(VARCHAR(3),[4 digit year]),'-'),
[example]=CASE WHEN [4 digit year] IS NOT NULL
THEN CONVERT(VARCHAR(30),GETDATE(),[4 digit year])
ELSE '-' END

FROM
@types
--------------------------------------------------------------------------
/*



Manipulating dates
------------------


Getting the CURRENT date can be done BY three functions: */
SELECT GETDATE()        --the local date and time
SELECT GETUTCDATE()     --the UTC or GMT date and time
SELECT CURRENT_TIMESTAMP--synonymous with GetDate()
-- When extracting parts of a DateTime you have some handy functions that 
-- return integers
-- DAY, MONTH, YEAR .. here we get the day, month and year as integers
SELECT DAY(GETDATE()),MONTH(GETDATE()),YEAR(GETDATE())

-- The functions DAY MONTH AND YEAR are shorthand for the equivalent 
-- DATEPART command,
but for more general use the DATEPART function
-- is more versatile

SELECT DATEPART(DAY,GETDATE()),DATEPART(MONTH,GETDATE()),
               
DATEPART(YEAR,GETDATE())


/*
DATEADD
-------


DATEADD will actually add a number of years, quarters, months,weeks,days, 
hours, minutes, seconds, or milliseconds to your specifced date. The format is as follows:



year (yy or yyyy)
quarter (qq or  q)
month (mm or  m)
week (wk or  ww) 
Day (dayofyear, dy, y, day, dd, d, weekday or dw)
hour (hh
minute (mi or  n),
second (ss or  s)
millisecond (ms)



In these examples we compare the date  with the DATEADDed date so you can see
the effect that the DATEADD is having to it*/
--
SELECT
'2007-01-01 00:00:00', DATEADD(YEAR,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(quarter,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(MONTH,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(dayofyear,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(DAY,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(week,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(weekday,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(hour,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(minute,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(second ,100,'2007-01-01 00:00:00.000')
SELECT '2007-01-01 00:00:00', DATEADD(millisecond,100,'2007-01-01 00:00:00.000')



--getting the current date can be done by three functions
SELECT GETDATE() --the loval date and time
SELECT GETUTCDATE() --the UTC or GMT date and time
SELECT CURRENT_TIMESTAMP--synonymous with GetDate()
/*

DATEDIFF
--------


DATEDIFF returns an integer of the difference between two dates expressed in Years,
quarters, Months,Weeks,Days,Hours,minutes,seconds or milliseconds (it counts the 
boundaries).*/


SELECT DATEDIFF(DAY,'1 feb 2006','1 mar 2006')--28
SELECT DATEDIFF(DAY,'1 feb 2008','1 mar 2008')--29. Hmm must be a leap year!
/*


We will give some practical examples of its use later on in the workshop
  



DATENAME
--------


Unlike DatePart, which returns an integer, DATENAME returns a NVarchar 
representing  the Year,quarter,Month,Week,day of the week,Day of the year,
Hour,minute, second or illisecond within the date. The Month and weekday 
are given in full from the value in the sysLanguages table.
*/
SELECT DATENAME (YEAR,GETDATE()) --2006
SELECT DATENAME (quarter,GETDATE()) --4
SELECT DATENAME (MONTH,GETDATE()) --October
SELECT DATENAME (dayofyear,GETDATE()) --285
SELECT DATENAME (DAY,GETDATE()) --12
SELECT DATENAME (week,GETDATE()) --42
SELECT DATENAME (weekday,GETDATE()) --Thursday
SELECT DATENAME (hour,GETDATE()) --9
SELECT DATENAME (minute,GETDATE()) --32
SELECT DATENAME (second ,GETDATE()) --8
SELECT DATENAME (millisecond,GETDATE()) --875


 

/*
DATEPART
--------

DATEPART returns an integer representing the part of the date requested in the 1st
parameter. You can use year (yy or yyyy), quarter (qq or q), month (mm or m),
dayofyear (dy or y) day (dd or d), week (wk or ww) , weekday (dw),hour (hh),
minute (mi or n), second (ss or s), or millisecond (ms) */


SELECT DATEPART(YEAR,GETDATE()) --2006
SELECT DATEPART(quarter,GETDATE()) --4
SELECT DATEPART(MONTH,GETDATE()) --10
SELECT DATEPART(dayofyear,GETDATE()) --285
SELECT DATEPART(DAY,GETDATE()) --12
SELECT DATEPART(week,GETDATE()) --42
SELECT DATEPART(weekday,GETDATE()) --4
SELECT DATEPART(hour,GETDATE()) --9
SELECT DATEPART(minute,GETDATE()) --32
SELECT DATEPART(second ,GETDATE()) --8
SELECT DATEPART(millisecond,GETDATE()) --875



/*

Formatting Dates
-----------------


Examples of calculating and formatting dates
*/
--To get the full Weekday name
SELECT DATENAME(dw,GETDATE())
--To get the abbreviated Weekday name (MON, TUE, WED etc)
SELECT LEFT(DATENAME(dw,GETDATE()),3)
--ISO-8601 Weekday number
SELECT DATEPART(dw,GETDATE())+(((@@Datefirst+3)%7)-4)
--Day of the month with leading zeros
SELECT RIGHT('00' + CAST(DAY(GETDATE()) AS VARCHAR),2)
--Day of the month without leading space
SELECT CAST(DAY(GETDATE()) AS VARCHAR)
--day of the year
SELECT DATEPART(dy,GETDATE())
--number of the week in the year
SELECT DATEPART(week,GETDATE())
--ISO-8601 number of the week of the year (monday as the first day of the week)
SET datefirst 1 SELECT DATEPART(week,GETDATE())
--you may need to preserve and restore the value
--full name of the month
SELECT DATENAME(MONTH,GETDATE())
--Abbreviated name of the month
SELECT LEFT(DATENAME(MONTH,GETDATE()),3)--not true of finnish or french!
--Number of the month with leading zeros
SELECT RIGHT('00' + CAST(MONTH(GETDATE()) AS VARCHAR),2)
--two-digit year
SELECT RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR),2)
--four-digit year
SELECT CAST(YEAR(GETDATE()) AS VARCHAR)
--hour (00-23)
SELECT DATEPART(hour,GETDATE())
--Hour (01-12)
SELECT LEFT(RIGHT(CONVERT(CHAR(19),GETDATE(),100),7),2)
--minute
SELECT DATEPART(minute,GETDATE())
--second
SELECT DATEPART(second,GETDATE())
--PM/AM indicator
SELECT RIGHT(CONVERT(CHAR(19),GETDATE(),100),2)
--time in 24 hour notation
SELECT CONVERT(VARCHAR(8),GETDATE(),8)
--Time in 12 hour notation
SELECT RIGHT(CONVERT(CHAR(19),GETDATE(),100),7)
--timezone (or daylight-saving)
SELECT DATEDIFF(hour, GETDATE(), GETUTCDATE())
----ordinal suffix for the date
SELECT SUBSTRING('stndrdthththththththththththththththththstndrdthththththththst'
,(DATEPART(DAY,GETDATE())*2)-1,2)
--full date (the variations are infinite. Here is one example
SELECT DATENAME(dw,GETDATE())+', '+ STUFF(CONVERT(CHAR(11),GETDATE(),106),3,0,
SUBSTRING('stndrdthththththththththththththththththstndrdthththththththst'
,(DATEPART(DAY,GETDATE())*2)-1,2))
--e.g. Thursday, 12th Oct 2006



/*

Calculating Dates by example
----------------------




*/
-- now
SELECT GETDATE()
-- Start of today (first thing)
SELECT CAST(CONVERT(CHAR(11),GETDATE(),113) AS datetime)
-- Start of tomorrow (first thing)
SELECT CAST(CONVERT(CHAR(11),DATEADD(DAY,1,GETDATE()),113) AS datetime)
-- Start of yesterday (first thing)
SELECT CAST(CONVERT(CHAR(11),DATEADD(DAY,-1,GETDATE()),113) AS datetime)
-- This time Next thursday (today if it is thursday)
SELECT DATEADD(DAY,((7-DATEPART(dw,GETDATE())+(((@@Datefirst+3)%7)+2)) % 7),GETDATE())
-- This time Last friday (today if it is friday)
SELECT DATEADD(DAY,-((7-DATEPART(dw,GETDATE())+(((@@Datefirst+3)%7)+3)) % 7),GETDATE())
-- Two hours time
SELECT DATEADD(hour,2,GETDATE())
-- Two hours ago
SELECT DATEADD(hour,-2,GETDATE())
-- Same date and time last month
SELECT DATEADD(MONTH,-1,GETDATE())
-- Start of the month
SELECT CAST('01 '+ RIGHT(CONVERT(CHAR(11),GETDATE(),113),8) AS datetime)
-- Start of last month
SELECT CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,GETDATE()),113),8) AS datetime)
-- Start of next month
SELECT CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,1,GETDATE()),113),8) AS datetime)
-- Ten minutes ago
SELECT DATEADD(minute,-10,GETDATE())
-- Midnight last night
SELECT CAST(CONVERT(CHAR(11),GETDATE(),113) AS datetime)
-- Midnight tonight
SELECT CAST(CONVERT(CHAR(11),DATEADD(DAY,1,GETDATE()),113) AS datetime)
-- Three weeks ago
SELECT DATEADD(week,-3,GETDATE())
-- Start of the week (this depends on your @@DateFirst setting)
SELECT DATEADD(DAY, -(DATEPART(dw,GETDATE())-1),GETDATE())
-- last year
SELECT DATEADD(YEAR,-1,GETDATE())
-- new year, this year
SELECT CAST('01 Jan'+ DATENAME(YEAR,GETDATE()) AS datetime)
-- new year, last year
SELECT CAST('01 Jan'+ DATENAME(YEAR,DATEADD(YEAR,-1,GETDATE())) AS datetime)
-- next christmas
SELECT CASE WHEN DATEPART(dy,GETDATE())<DATEPART(dy,'25 Dec'+ + DATENAME(YEAR,GETDATE()))
THEN CAST('25 Dec'+ + DATENAME(YEAR,GETDATE()) AS datetime)
ELSE CAST('25 Dec'+ CAST(DATEPART(YEAR,GETDATE())+1 AS VARCHAR) AS datetime) END

/*

Date Conversions
-----------------



The DATETIME data type stores the Date and time data from January 1, 1753 to
December 31, 9999, to an accuracy of one 3.33 milliseconds. Values are rounded.
Values are stored as two 4-byte integers:


. The first 4 bytes store the number of days +- from the base date, January 1, 1900.
The base date is the system reference date.
. The second 4 bytes store the time of day represented as the number of milliseconds
after midnight.



Values for datetime earlier than January 1, 1753 are not permitted.

When converting from SQL Server dates to Unix timestamps, the dates are rounded to the
nearest second (Unix timestamps are only accurate to the nearest second)

SQL Server date to UNIX timestamp (based on seconds since standard epoch of 1/1/1970)
*/


SELECT DATEDIFF(second,'1/1/1970',GETDATE())

-- UNIX timestamp to SQL Server
SELECT DATEADD(second, 1160986544, '1/1/1970') /*


Using dates
-----------




When storing dates, always us the datetime data type. Do not feel tempted to use
tricks such as storing the year, month or day as integers, with the idea that this
will help retrieval and aggregation for reports. It never does. The manipulation of
datetimes is so critical to SQL Server's performance that it is highly optimised.
indexes based on DateTimes work very well, sort properly, and allow fast partitioning
on a variety of criteria such as week, month, year-to-date and so on.
If, for example, you store a list of purchases by date in a table such as PURCHASES
you can find the sum for the previous week by... */


SELECT SUM(total) FROM purchases
WHERE purchaseDate BETWEEN DATEADD(week,-1,GETDATE()) AND GETDATE()
--this will pick up an index on PurchaseDate

--what about sales since the start of the week
SELECT SUM(total) FROM purchases
WHERE purchaseDate BETWEEN
DATEADD(DAY, -(DATEPART(dw,GETDATE())-1),GETDATE()) AND GETDATE()

--Want a daily total?
SELECT CONVERT(CHAR(11),PurchaseDate,113),
SUM(total) FROM purchases
GROUP BY CONVERT(CHAR(11),PurchaseDate,113)
ORDER BY MIN(PurchaseDate)

--Or to find out which days of the week were the best?
SELECT DATENAME(dw,PurchaseDate),
[No. Purchases]=COUNT(*), [revenue]=SUM(total) FROM [purchases]
GROUP BY DATENAME(dw,PurchaseDate), DATEPART(dw,PurchaseDate)
ORDER BY DATEPART(dw,PurchaseDate)


--Want a week by week total?
SELECT 'Week '+DATENAME(week,purchaseDate)+' '+DATENAME(YEAR,purchaseDate),
SUM(total) FROM purchases
GROUP BY 'Week '+DATENAME(week,purchaseDate)+' '+DATENAME(YEAR,purchaseDate)
ORDER BY MIN(InsertionDate)
--(you'd miss weeks where nothing was purchased if you did it this way.)



/* The LIKE expression can be used for searching for datetime values.
If, for example, one wants to search for all purchases done at 9:40, one can find
a match by the clause WHERE purchaseDate LIKE '%9:40%'. */
SELECT * FROM [purchases]
WHERE purchaseDate LIKE '%9:40%'
--or all purchases in the month of february
SELECT COUNT(*) FROM [purchases]
WHERE purchaseDate LIKE '%feb%'
--all purchases where there is a 'Y' in the month (matches only May!)
SELECT DATENAME(MONTH, insertionDate), COUNT(*) FROM [purchases]
WHERE purchaseDate LIKE '%y%'
GROUP BY DATENAME(MONTH, purchaseDate)

/* this 'Like' trick is of limited use and should be used with considerable caution as
it uses artifice to get its results*/



This article has been viewed 35693 times.
Robyn Page

Author profile: Robyn Page

Robyn Page is a consultant with Enformatica and USP Networks. She is also a well known actress, being most famous for her role as Katie Williams, barmaid and man-eater in the Television Series Family Affairs, when she was nominated as 'Most sexy newcomer' at the British Soap awards.

Search for other articles by Robyn Page

Rate this article:   Avg rating: from a total of 120 votes.


Poor

OK

Good

Great

Must read
 
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: awesome
Posted by: alphagrl (view profile)
Posted on: Thursday, October 19, 2006 at 10:23 AM
Message: I have spent countless hours dealing with formatting of dates/times. I wish I could have found this article years ago. Very handy for reference.

Subject: missing results
Posted by: fels (view profile)
Posted on: Thursday, October 19, 2006 at 6:07 PM
Message: Excellent articles.
Please add statements results to complement.

Subject: Wow
Posted by: horace (view profile)
Posted on: Thursday, October 19, 2006 at 6:32 PM
Message: I have never really had much of an issue with date time field in by work but the work required was always very basic.
This article has really opened my eyes and blown me away.

Thankyou

Subject: More on first/last day of week/month/quarter/year/etc
Posted by: IDisposable (view profile)
Posted on: Thursday, October 19, 2006 at 10:15 PM
Message: I wrote a fairly extensive blog post on getting first / last date for day, week, month, quarter, year here
http://musingmarc.blogspot.com/2006/07/more-on-dates-and-sql.html

Subject: re: missing results
Posted by: Robyn Page (view profile)
Posted on: Friday, October 20, 2006 at 3:17 AM
Message: Yes, we did wonder whether to add all the statements results but decided in the end that it would bulk up the code somewhat to do it in every case. Has anyone else an opinion on this? It is something we could add in future 'workshops'

Subject: Wonderful
Posted by: WebMister (view profile)
Posted on: Friday, October 20, 2006 at 3:38 AM
Message: I wish the BOL was set out like this. It makes it so much clearer.
Spot on, Robyn.

Subject: Couple of comments
Posted by: nigelrivett (view profile)
Posted on: Friday, October 20, 2006 at 5:23 AM
Message: Good article (although I haven't read much of it)

It mentions using the unambiguous iso format but could also mention
yyyymmdd hh:mm:ss.mmm
which is my preferred option - it can be used without the time whereas the iso format can't.

For calculating dates (start of month etc.) it is faster to use dateadd than to convert to character. Must admit I always use the convert to character unless speed is important as it is more readable.

Subject: Myth Buster
Posted by: two_calls (view profile)
Posted on: Friday, October 20, 2006 at 7:20 AM
Message: Well, so much for the notion that Beauty and Intelligence are rarely found in such quantities in our line of work...
GREAT FORMAT - I like to keep good examples of working cose in my Solution Explorer for reference. The obscure MS examples rarely work for my beginners level of understanding.

Well done - Waiting for some more reference material...

Subject: Re: Couple of comments
Posted by: Robyn Page (view profile)
Posted on: Friday, October 20, 2006 at 7:41 AM
Message: --I suspect the character conversion method may be slower
--but I can't prove it because there isn't much in it
--all date functions seem very fast.
--here is the test harness I used. Can anyone think
--of a better one?
--like Nigel, I'll continue to use the Character version as it is
--easier to remember and pretty versatile
--Anyone know better?

set nocount on
declare @ii int
declare @start Datetime
Declare @bucket table (theDate datetime)
Declare @otherbucket table (theDate datetime)

--test out getting the date ten thousand times
--two different ways
--You need to change the order of testing to ge a comparison
select @ii=10000, @start=GetDate()

while @ii>0
begin
insert into @bucket(theDate)
Select convert(char(11),getdate(),113)
select @ii=@ii-1
end
--report how long it took
Select [time taken (ms) is ]=Datediff(ms,@Start,GetDate())--1453ms


--set the timer and use the DateDiff trick
select @ii=10000, @start=GetDate()
while @ii>0
begin
insert into @otherbucket(theDate)
Select Dateadd(dd, DateDiff(dd,0,GetDate()),0)
select @ii=@ii-1
end
--report how long it took
Select [time taken (ms) is ]=Datediff(ms,@Start,GetDate())--1423ms


Subject: Very, Very Cool
Posted by: ByrdMan (view profile)
Posted on: Friday, October 20, 2006 at 10:59 AM
Message: Robin, you are the fliest, geekiest chick that has ever come across my path. Damn good article, as well as your SQL Backup (which has helped me tremendiously). Geez, where have you been all my life!!! Kudos :)

Subject: Birdman: very very cool
Posted by: Robyn Page (view profile)
Posted on: Friday, October 20, 2006 at 2:10 PM
Message: Come on. I expect you say that to all the DBAs you meet!

Subject: Great Work
Posted by: rmallamace (view profile)
Posted on: Saturday, October 21, 2006 at 9:09 AM
Message: Why can't all examples be this in depth?
The only suggestion I can give for future examples is include a print statement with the comments/code - then you can see it in the resutls as well

Subject: Almost perfect!
Posted by: Auke (view profile)
Posted on: Wednesday, October 25, 2006 at 3:11 AM
Message: /*
Very good article! I bookmarked it immediately ;-)
But I think the ISO week is incorrect... :-(
For instance for today (oktober 25th, 2006) it returns week 44 and I'm quite sure it's 43!
*/

--ISO-8601 number of the week of the year (monday as the first day of the week) SET datefirst 1 SELECT DATEPART(week,GETDATE()) --you may need to preserve and restore the value

/*
I've been struggling with the whole ISO thing myself and after trying to get things 'clean' (as in a single line) for too long, I decided to do things the 'easy' way (see below).
*/

CREATE FUNCTION
ISOweek
(
@DATE datetime
)
RETURNS INT
AS
BEGIN
DECLARE @ISOweek int
SET @ISOweek = DATEPART(wk, @DATE) + 1 - DATEPART(wk, CAST(DATEPART(yy, @DATE) as CHAR(4)) + '0104')

--Special cases: Jan 1-3 may belong to the previous year
IF (@ISOweek = 0)
SET @ISOweek = dbo.ISOweek(CAST(DATEPART(yy,@DATE) - 1 AS CHAR(4)) + '12' +
CAST(24 + DATEPART(DAY, @DATE) AS CHAR(2))) + 1

--Special case: Dec 29-31 may belong to the next year
IF ((DATEPART(mm,@DATE) = 12) AND ((DATEPART(dd, @DATE)-DATEPART(dw, @DATE)) >= 28))
SET @ISOweek = 1
RETURN(@ISOweek)
END

/*
Furthermore in some cases I needed to show the year as well. For instance januari 1st 2005 is in week 52 of year 2004.
*/
CREATE FUNCTION
ISOyyyyww
(
@DATE datetime
)
RETURNS varchar(6)
AS
BEGIN
DECLARE @ISOyear int
DECLARE @ISOweek int

DECLARE @YEAR int
DECLARE @MONTH int

SET @ISOweek = dbo.ISOweek(@date)

SET @YEAR = DATEPART(year, @date)
SET @MONTH = DATEPART(month, @date)

SET @ISOyear = @year
IF @MONTH = 1 and @ISOWEEK > 50 SET @ISOyear = @YEAR - 1
IF @MONTH = 12 and @ISOWEEK = 1 SET @ISOyear = @YEAR + 1

RETURN convert(varchar(4), @ISOyear) + right('0' + convert(varchar(2), @ISOweek), 2)
END

/*
If you have a 'cleaner' method I'm very interested!
*/

Subject: Great article
Posted by: jamesperry (view profile)
Posted on: Wednesday, October 25, 2006 at 3:21 AM
Message: A great article, i often get asked questions regarding the datetime field within SQL Server so now i can pass any confused developers this article.

Subject: Better testing
Posted by: Auke (view profile)
Posted on: Wednesday, October 25, 2006 at 4:28 AM
Message: --Hi, test seems quite ok, but don't use the tables. it will flood the tempdb and make it harder to compare (the order of testing shouldn't matter any more).
--Added my own function which uses the fact that datetimes are stored as a float (integer part = date, decimal part = time)
--The datediff function seems to the fastest!

set nocount on
declare @ii int
declare @start Datetime
declare @dummy Datetime

--test out getting the date hundred thousand times
--three different ways
select @ii=100000, @start=GetDate()
while @ii>0
begin
set @dummy = convert(char(11),getdate(),113)
set @ii=@ii-1
end
--report how long it took
Select [time taken (ms) is ]=Datediff(ms,@Start,GetDate())--1500ms

--set the timer and use the DateDiff trick
select @ii=100000, @start=GetDate()
while @ii>0
begin
set @dummy = Dateadd(dd, DateDiff(dd,0,GetDate()),0)
set @ii=@ii-1
end
--report how long it took
Select [time taken (ms) is ]=Datediff(ms,@Start,GetDate())--593ms

--Set the timer and use the convert to float and floor
select @ii=100000, @start=GetDate()
while @ii>0
begin
set @dummy = convert(datetime, floor(convert(float, getdate())))
set @ii=@ii-1
end
--report how long it took
Select [time taken (ms) is ]=Datediff(ms,@Start,GetDate())--656ms

Subject: Rats! Copy-paste into Management Studio bites!
Posted by: SAinCA (view profile)
Posted on: Wednesday, October 25, 2006 at 3:37 PM
Message: Admirable thoroughness and "global" examples - THANKS.

Any chance the next workbench could use paragraph ends instead of line breaks? Copying the examples into SS2K5 MS results in just 19 lines, some over 20K characters long...

Subject: The Best !
Posted by: bisjom (view profile)
Posted on: Wednesday, October 25, 2006 at 9:32 PM
Message: This is the one that i have been looking for ages..
Really helpfull..
Thanks Robyn!

Subject: Excellenet Work
Posted by: Kamran (view profile)
Posted on: Thursday, November 09, 2006 at 10:24 AM
Message: Excellent Work Done by Robyn.But one thing for which i was searching Datetime functions in SQL server is the last date of the month which is missing in it.
Can you tell me how to get Last date of the month.

Subject: End of month
Posted by: Auke (view profile)
Posted on: Friday, November 10, 2006 at 3:33 AM
Message: @Kamran

What about start of next month minus one day? ;-)

SELECT DATEADD(d, -1, (CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,1,GETDATE()),113),8) AS datetime)))

Subject: exelent examples
Posted by: erikb68 (view profile)
Posted on: Friday, November 10, 2006 at 1:31 PM
Message: Just keep on doing it the way You are... Perhaps You have some thoughts on topics like "T-SQL best pratices" or "T-SQL Tuning" ?

Subject: Elapsed time
Posted by: iordan (view profile)
Posted on: Tuesday, December 12, 2006 at 3:46 PM
Message: When time is to be considered more like an interval rather than a fixed point, e.g. measuring the time it takes you to write an article as good as Robin's vs. the time you get up in the morning, the value easily can be >24 h. Then the "datetime" format is not quite useful - problems with the reference point ("Jan 1, 1900"), problems with data entry and displaying etc.

So, I use text - char(8) with pattern "hh:mm:ss". This can be easily converted into seconds and added to whatever base point (datetime) you choose. Is there another way?

Subject: End of month
Posted by: rmallamace (view profile)
Posted on: Tuesday, January 09, 2007 at 7:36 PM
Message: The end of month query is fine if you are only storing dates, but if you are storing time as well make sure your calculation is the start of next month minus one second to capture times after 00:00:00.000

SELECT DATEADD(s, -1, (CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,1,GETDATE()),113),8) AS datetime)))

Subject: re:elapsed time
Posted by: Robyn Page (view profile)
Posted on: Wednesday, January 10, 2007 at 3:46 AM
Message: iordan's approach is a good one because one can see instantly how much time has elapsed from looking at the table. However, one should, I believe, use a user-defined type with a rule, to check for valid data, and you'd have to be very careful about date calculations. I'd have to add that when I have to store time-intervals, I use an integer based on the number of seconds in the interval, and this seems to be the general consensus approach. This certainly makes date-arithmetic and interval-arithmetic a lot easier. (e.g. what is the average time I spend writing these workshops)

Subject: Newbie Question
Posted by: mkn (view profile)
Posted on: Wednesday, January 24, 2007 at 2:17 PM
Message: I am starting to re-write my travel reservation system into SQL from (another) database. I set up my flight schedule file with smalldatetime containing both date and departure time. But I have just realized it's tricky to do comparisons like "get all flights between these dates" due to time content. Can anyone advise me on the approved way to do this. For example, should I store the date in one smalldatetime field and the time in another?
Thanks in advance, Malcolm Needham

Subject: Re: Newbie Question
Posted by: Robyn Page (view profile)
Posted on: Thursday, January 25, 2007 at 11:57 AM
Message: No, I can assure you it is a lot more difficult to do the "get all flights between these dates" if you have two columns as you are suggesting. I'd recommend you to have the date and time in one column. then you can easily select all flights between two dates by
SELECT (flight information) from (table) where (departure time) between (earliest date) and (latest date)
in the article, there should be all the SQL you need to extract any information from your 'departure date/time' column
Good luck with the application, Malcolm!

Subject: Awesome reference
Posted by: Anonymous (not signed in)
Posted on: Wednesday, February 21, 2007 at 11:11 AM
Message: Robyn,

Thank you for the wonderful reference. One thing I didn't see and have been struggling with is returning data for work days only. This will need to exclude weekends and holidays. Any ideas?

Subject: Wonderful Works
Posted by: Anonymous (not signed in)
Posted on: Sunday, February 25, 2007 at 8:40 PM
Message: Thanks for this article.
I wonder if BOL will give more details as in this article.
Hope to hear more from you.
Thanks again Robyn,

Subject: Thanks
Posted by: Anonymous (not signed in)
Posted on: Wednesday, March 21, 2007 at 2:54 PM
Message: Thanks for the reference, is really amazing all the things that you can do with datetime information.

Subject: Excellent Tutorial
Posted by: Anonymous (not signed in)
Posted on: Wednesday, April 25, 2007 at 8:03 AM
Message: Better than any reference manual!

Subject: Awesome!!
Posted by: Anonymous (not signed in)
Posted on: Tuesday, May 22, 2007 at 2:09 PM
Message: Great work, thanks!

Subject: Bookmark set.
Posted by: Kelly Logan (not signed in)
Posted on: Friday, May 25, 2007 at 8:49 AM
Message: Excellent work, Robyn.

Thank you for a very clear and concise page on dates and times in SQL Server queries.

Kelly Logan

Subject: GETDATE()
Posted by: Anonymous (not signed in)
Posted on: Tuesday, May 29, 2007 at 2:14 PM
Message: Would reading all this increase one's likelihood of actually getting a date with the author?

Subject: Nice one
Posted by: Arun Sabat (not signed in)
Posted on: Thursday, June 14, 2007 at 8:32 AM
Message: Thank you posting this. I got lot more ideas.

Subject: Date of the latest friday??
Posted by: Karen (not signed in)
Posted on: Wednesday, June 20, 2007 at 3:02 PM
Message: I'm trying to pull the date of the previous Friday. Example: Today is 06/20/2007, I need to pull 06/15/2007. So no mater what day of the week, I'm trying to pull the date of the last occuring Friday. I'm thinking it will have to reside within a while statement. True?

Thanks in advance!

Subject: Date of the latest friday??
Posted by: Karen (not signed in)
Posted on: Wednesday, June 20, 2007 at 3:06 PM
Message: I'm trying to pull the date of the previous Friday. Example: Today is 06/20/2007, I need to pull 06/15/2007. So no mater what day of the week, I'm trying to pull the date of the last occuring Friday. I'm thinking it will have to reside within a while statement. True?

Thanks in advance!

Subject: Re Date of the latest friday??
Posted by: Phil Factor (view profile)
Posted on: Wednesday, June 27, 2007 at 11:27 AM
Message: False!

SELECT DATEADD(DAY,-((7-DATEPART(dw,GETDATE())+(((@@Datefirst+3)%7)+3)) % 7),GETDATE())

That gives you the current time, last friday, whatever your DateFirst setting.

Subject: "Regardless of Datefirst setting"
Posted by: ArchieInUK (not signed in)
Posted on: Tuesday, July 17, 2007 at 9:15 AM
Message: I did not get any of the above code working using different datefirst setting!

The code below will ALWAYS gives the begining of last monday with respect to getdate(), regardless of datefirst setting.

select CONVERT(smalldatetime, CONVERT(varchar,GETDATE(), 107)) - (DATEDIFF(day, 0, GETDATE()) % 7 + 7) as 'Last Monday'

Subject: Date Formats
Posted by: Anonymous (not signed in)
Posted on: Friday, August 03, 2007 at 11:49 AM
Message: You go techno geek girl! Awesome. Thanks

Subject: Time Averaging
Posted by: John (view profile)
Posted on: Monday, August 06, 2007 at 3:23 PM
Message: I have an ASP page that creates and populates an HTML table from a SQL table. The SQL table contains two datetime fields (SignInTime and RepTimeIn). In the SELECT statement that populates the HTML table, I use the following code to populate a third column called "Wait Time" that is the difference between the two fields named above:

"convert(varchar,RepTimeIn-SignInTime,108) Wait"

This works fine. However, in another location on the same page I would like to display the average of all of these "wait times", but I have been unable to do so. Can anyone suggest a possible solution?


Subject: Thank you
Posted by: Lucien (not signed in)
Posted on: Wednesday, August 22, 2007 at 4:22 AM
Message: Thank you, Love you, this is not the first time i've stumbled upon your name when i've had an sql question. Again, thanks.

Subject: Thank You
Posted by: Salman (view profile)
Posted on: Wednesday, August 29, 2007 at 4:55 AM
Message: when ever i have issues with my dates
i come here. Robyn Page Date Work Bench


Subject: Week Of Quarter
Posted by: Suresh (view profile)
Posted on: Friday, September 14, 2007 at 2:01 AM
Message: Do we have any function to display the Week no of a Quarter.

I dont want the week no of the year.

Subject: WOW
Posted by: Anonymous (not signed in)
Posted on: Thursday, October 18, 2007 at 4:42 PM
Message: Great article! This is exactly what I needed. Thank you so much. I think I'm in love!

Subject: Mind Blowing
Posted by: eknath.dohale@gmail.com (not signed in)
Posted on: Wednesday, November 21, 2007 at 6:23 AM
Message: This is the Mind Blowing Article.

Subject: Thank You
Posted by: TREY PAIGE (view profile)
Posted on: Thursday, January 17, 2008 at 2:49 PM
Message: You are Awesome

Subject: Thanks for this article
Posted by: Ermond (not signed in)
Posted on: Monday, January 28, 2008 at 6:04 AM
Message: Really very helpful this article.
Thanks for it. I needed something like this desperately

Subject: FIND Last Thursday From Current date
Posted by: Mitesh Oswal (not signed in)
Posted on: Monday, February 18, 2008 at 4:10 AM
Message:
DECLARE @DATE DATETIME
SET @DATE='02/28/2007'
SELECT CASE WHEN DATEPART(DW,@DATE)>3
THEN DATEADD(DD,-(DATEPART(DW,@DATE)-4),@DATE)
ELSE DATEADD(DD,-(DATEPART(DW,@DATE)+3),@DATE)
END

Subject: datetime format
Posted by: Margot (not signed in)
Posted on: Sunday, March 23, 2008 at 5:17 PM
Message: This has saved my sanity, thank you

Subject: Integer convert to datetime
Posted by: Anonymous (not signed in)
Posted on: Thursday, June 19, 2008 at 8:32 AM
Message: I am at a very elementary level of understanding. I have integer data that I needs to be converted to datetime. So I can then format it from seconds to hours.

Subject: good one
Posted by: Anonymous (not signed in)
Posted on: Friday, June 27, 2008 at 4:17 PM
Message: Got good help from this article.
Thanks for contribution

Subject: good for sql starters
Posted by: rajesh (view profile)
Posted on: Monday, June 30, 2008 at 7:37 AM
Message: hey robyn ...keep it up..really nice article.

Subject: Re: Thanks
Posted by: Sayyad (not signed in)
Posted on: Sunday, July 06, 2008 at 9:53 PM
Message: Its really helpful for beginners and old timers as well.

Thanks

best regards
Sayyad

Subject: Dates, time series and multiple datasources
Posted by: brendans (view profile)
Posted on: Monday, October 20, 2008 at 2:16 PM
Message: For information on how to pull date/event based info from multiple data sources, see this:

http://www.izenda.com/Site/KB/CodeSamples/Combining-Multiple-Event-Based-Fields-with-UNION

Subject: The workbench.
Posted by: Robyn Page (view profile)
Posted on: Friday, December 12, 2008 at 12:55 PM
Message: Thanks to 'y all for the kind comments. i keep wondering whether to do an update of this but it seems to have stood the test of time.

Subject: Calendar table
Posted by: Chris Turner (view profile)
Posted on: Tuesday, February 17, 2009 at 5:57 AM
Message: Excellent article Robyn, thanks. One addition that I've found very useful is to create a calendar table, which contains all the dates for the next ten years. This then allows me to hold against each date the period start date, period end date, whether or not it's a working day and much more besides. If you have a financial calendar that starts at an odd time of the year (26th of June in one case) or clients/customers that use periods that are different to your own, it allows you to hold those dates as well.

It's an overhead at the end of each year to extend the table for another twelve months, but the benefits it brings are definitely worth it. Oh, and all the dates in it are stored as datetimes...

C

 










Phil Factor
Finding Stuff in SQL Server Database DDL
 You'd have thought that nothing would be easier than using SQL Server Management Studio (SSMS) for searching... Read more...



 View the blog
Implementing User-Defined Hierarchies in SQL Server Analysis Services
 To be able to drill into multidimensional cube data at several levels, you must implement all of the... Read more...

Using the Filtering API with the SQL Comparison SDK
 Red Gate's SQL Comparison SDK provides a means to compare and synchronize database schemas and data... Read more...

SQL Toolbelt 2008: Predominantly an Engineering Task
 The conversion of the Red-Gate tools to be compatible with SQL Server 2008 might not seem, on first... Read more...

SQL Response: The dim sum interview
 Richard Morris met David and Nigel of the SQL Response team, in a dim sum Restaurant in Cambridge. They... Read more...

Writing Efficient SQL: Set-Based Speed Phreakery
 Phil Factor's SQL Speed Phreak challenge is an event where coders battle to produce the fastest code to... Read more...

Beginning SQL Server 2005 Reporting Services Part 1
 Steve Joubert begins an in-depth tour of SQL Server 2005 Reporting Services with a step-by-step guide... Read more...

Ten Common Database Design Mistakes
 Database design and implementation is the cornerstone of any data centric project (read 99.9% of... Read more...

Beginning SQL Server 2005 Reporting Services Part 2
 Continuing his in-depth tour of SQL Server 2005 Reporting Services, Steve Joubert demonstrates the most... Read more...

SQL Server Full Text Search Language Features
 SQL Full-text Search (SQL FTS) is an optional component of SQL Server 7 and later, which allows fast... Read more...

Creating CSV Files Using BCP and Stored Procedures
 Nigel Rivett demonstrates some core techniques for extracting SQL Server data into CSV files, focussing... Read more...

Over 150,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.

Join Simple Talk