SQL

SQL

Saturday, February 2, 2013

Working with Dates


As you begin to work more with data, you begin to understand the importance of working with dates. Data really has no meaning unless it is specific. As you begin to work with WHERE clauses, you are going to want to drill down to specific time frames.
You may want to see data within a specific date range, in those cases your WHERE clauses would look like this:
Where [Service Date] between '01-01-2013' and '12-01-2013'
Or you could have simply used DATEPART
Where DATEPART(YEAR,[Service Date]) = '2013'

If you will be using a script on a regular basis that may require a few date changes in several parts of the code, you may want to use DECLARATIONS. Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values by using either a SET or SELECT statement. 
In our example declarations will allow you to set what the date will be at the beginning of the statement, and that one date will be referenced when ever a date range is needed.
DECLARE @FromDos datetime,
        @ThruDOS datetime

SET @FromDos        = '01/01/2012' 
SET @ThruDOS        = '12/31/2012' 

So now, when a date is needed, you simply insert @FromDos and/or @ThruDOS.

Where [Service Date] between   @FromDos  and @ThruDOS               

Try it and see how it works for you.