Вы находитесь на странице: 1из 15

Microsoft Virtual Labs

Working with the new DATE


datatype in SQL Server 2008
Working with the new DATE datatype in SQL Server 2008

Table of Contents
Working with the new DATE datatype in SQL Server 2008 .................................................... 1
Exercise 1 Exploring DATE and TIME datatypes.........................................................................................................2
Exercise 2 Working with the DATE/TIME datatypes ...................................................................................................6
Exercise 3 Modifying T-SQL to benefit from the date datatype ...................................................................................9
Working with the new DATE datatype in SQL Server 2008

Working with the new DATE datatype in


SQL Server 2008
After completing this lab, you will be better able to:
Objectives  Use the new date/time related datatypes and their related functions

In this lab you will identify the limitations of working with date and time data in
Scenario previous editions of SQL Server 2005. You will identify the new datatypes and
new functions that release with SQL Server 2008 and make modifications to
existing data by modifying database structures, and implementing date/time best
practices.

SQL Server 2008 support for date and time data


In SQL Server 2008 additional support for date and time data is provided by the
introduction of new datatypes.

The introduction of these new datatypes allow you to better store and work with
date and time data, including multiple time zones and enhanced date calculations.

The new datatypes consist of:


• datetime2
• date
• time
• datetimeoffset

Besides these new datatypes a new set of date and time related functions are
introduced.

Note: This lab is tested with SQL Server 2008 codename ‘Katmai’ CTP 4. The
documentation and instructions in this lab is pre-release and is subject to change
in future release.

Estimated Time to 45 Minutes


Complete This Lab

Computers used in this


SQL2008CTP
Lab
The password for the Administrator account on all computers in this lab is:
Pass@word1.

Page 1 of 13
Working with the new DATE datatype in SQL Server 2008

Exercise 1
Exploring DATE and TIME datatypes

Scenario
In this exercise, you will explore the new DATE and TIME datatypes in SQL Server 2008.

Note: Lab Scripts - In order to assist you completing the hands-on-labs a .sql script file for every exercise in this lab
has been created inside the virtual machine. The scripts for this lab can be found on the desktop under the SQL 2008
HOLs shortcut.

Tasks Detailed Steps


1. Start SQL Server a. Click Start | All Programs | Microsoft SQL Server code name Katmai | SQL
Management Studio Server Management Studio menu.
b. Click ‘Connect’ in the “Connect to Server” dialog box after ensuring the
following settings:
• Server type: Database Engine
• Server name: SQL2K8
• Authentication: Windows Authentication
Note: You may need to change the server name if required.
2. Create a LABDB a. Click on ‘New Query’ in the standard toolbar.
database b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or by
pressing ‘F5’

CREATE DATABASE LABDB


3. Identify the new Note: Information - sys.systypes is a system view that will keep track of all datatypes
datatypes defined in the SQL Server 2008 Database Engine
a. In the same query window, delete the previous statement(s).
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

select * from sys.systypes where name like '%date%' or name like '%time%'

The query result will look similar as in the picture below:

Page 2 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
Note that the following datatypes are new in SQL Server 2005: Datetime2,
datetimeoffset, date, time
4. Create a table with a. In the same query window, delete the previous statement(s).
the new datatypes b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

USE LABDB
GO
CREATE TABLE TBL_NewDatetimetypes (DateValue date, Timevalue Time,
DateTimeOffset datetimeoffset, Datetime2value datetime2)
5. Insert data in the a. In the same query window, delete the previous statement(s).
table b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

INSERT INTO TBL_NewDatetimetypes values


(SYSDATETIME(),SYSDATETIME(),SYSDATETIMEOFFSET(),SYSUTCDA
TETIME())

Note: The above statement is using the following functions:

SYSDATETIME - Returns the current database system timestamp as a datetime2(7)


value. The database time zone offset is not included. This value is derived from the
operating system of the computer on which the instance of SQL Server is running.

SYSDATETIMEOFFSET - Returns the current database system timestamp as a


datetimeoffset(7) value. This value is derived from the operating system of the
computer on which the instance of SQL Server is running. SYSDATETIME and
SYSUTCDATETIME have more fractional seconds precision than GETDATE and
GETUTCDATE. SYSDATETIMEOFFSET includes the system time zone offset.
SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET can be assigned
to a variable of any of the date and time types.

SYSUTCDATETIME - Returns the current database system timestamp as a datetime


value. The database time zone offset is not included. This value represents the current
UTC time (Coordinated Universal Time). This value is derived from the operating
system of the computer on which the instance of SQL Server is running.
c. In the same query window, delete the previous statement(s).
d. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

SELECT * FROM TBL_NewDatetimetypes

The query result will look similar as in the picture below:

Page 3 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps

6. Understanding the Note: Based on the previous query results you should understand that the new
stored data datatypes in SQL Server support the following storage:

This will allow you for a more granular storage of date and time data in SQL Server
2008.

Page 4 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
7. Using the Note: Information - The datetimeoffset datatype allows you to store the timezone
datetimeoffset identifier together with the date value.
datatype
a. In the same query window, delete the previous statement(s).
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

Create table tbl_timezones (Entryid int identity(1,1), Currenttime datetimeoffset)


insert into tbl_timezones (currenttime)
values ('1998-09-20 7:45:50.71345 -5:00')
insert into tbl_timezones (currenttime)
values ('1956-01-27 6:45:50.00000 -3:00')
insert into tbl_timezones (currenttime)
values ('1972-12-18 7:45:50.71345 +1:00')
insert into tbl_timezones (currenttime)
values ('2005-01-20 7:12:50.71345 +9:00')
insert into tbl_timezones (currenttime)
values ('2005-01-20 01:00:00.00000 +4:00')
8. Use the DATEPART Note: Information - The DATEPART function has been extended to return the
function to return the timezone value from a given timezone, the TZoffset value is returned in a number,
timezone offset for representing the number in minutes from GMT standard time. So PST (GMT - 7) will
the current database return the value of -420.
a. In the same query window, delete the previous statement(s).
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

select datepart(TZoffset,sysdatetimeoffset())

Note: Depending on the server timezone settings this will return the value in minutes
from the GMT standard time. This will be -420 for PST, 60 for GMT+1
9. Use the a. In the same query window, delete the previous statement(s).
SWITCHOFFSET b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
function to return a
by pressing ‘F5’
date in a different
timezone
select currenttime,SWITCHOFFSET ( currenttime,
datepart(TZoffset,sysdatetimeoffset())) as TimeinCurrentTimezone
from tbl_timezones

The query result will look similar to:

Page 5 of 13
Working with the new DATE datatype in SQL Server 2008

Exercise 2
Working with the DATE/TIME datatypes

Scenario
In this exercise you will identify some limitations of the datetime and smalldatetime datatype in previous editions of
SQL Server and you will take corrective actions to address those limitations.

Tasks Detailed Steps


Complete the following 6 a. Click Start | All Programs | Microsoft SQL Server code name Katmai | SQL
tasks on: Server Management Studio menu.
b. Click ‘Connect’ in the “Connect to Server” dialog box after ensuring the
SQL2008CTP following settings:
• Server type: Database Engine
1. Start SQL Server • Server name: (local)
Management Studio
• Authentication: Windows Authentication
Note: You may need to change the server name if required.
2. Create a new table to Note: Information - It is very common that when working with date data, the mistake
store is made by chosing the wrong datatype in a database design. In this example we will
'HistoricalEventData' purposely implement the wrong datatype, and then take corrective action.
a. Click on ‘New Query’ in the standard toolbar.
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

USE LABDB
GO
if object_id('tbl_historicalEvents') is not null
drop table tbl_historicalEvents

create table tbl_historicalEvents (EventID int IDENTITY (1,1),


Eventname nvarchar(200),
Eventdate datetime)

You will notice that this table gets created successfully.


3. Insert historical data a. In the same query window, delete the previous statement(s).
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

insert into tbl_historicalEvents (Eventname, Eventdate)


values ('Birthday of Wolfgang Amadeus Mozart', '01/27/1756')

Page 6 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps

insert into tbl_historicalEvents (Eventname, Eventdate)


values ('Universal declaration of Human Rights', '12/10/1948')
insert into tbl_historicalEvents (Eventname, Eventdate)
values ('Birthday of Johan Sebastian Bach', '03/21/1685')

Note: The last statement will fail with the following error:

Msg 242, Level 16, State 3, Line 5


The conversion of a varchar data type to a datetime data type resulted in an out-of-
range value.

Note: This error occurs because the date value you are trying to insert falls outside
the scope of the datetime datatype. (01-01-1753 through 9999-12-31)
4. Recreate the table a. In the same query window, delete the previous statement(s).
using the new date b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
datatype
by pressing ‘F5’

USE LABDB
GO
if object_id('tbl_historicalEvents') is not null
drop table tbl_historicalEvents

create table tbl_historicalEvents (EventID int IDENTITY (1,1),


Eventname nvarchar(200),
Eventdate date)

You will notice that this table gets created successfully


5. Insert historical data Note: Information - By modifying the datatype to date, the scope of the date values
you want to store allows you to store ranges from 0001-01-01 through 9999-12-31.
Since the date datatype does not store the time part as the datetime datatype does, the
actual storage in bytes internally will be less.
a. In the same query window, delete the previous statement(s).
b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

insert into tbl_historicalEvents (Eventname, Eventdate)


values ('Birthday of Wolfgang Amadeus Mozart', '01/27/1756')
insert into tbl_historicalEvents (Eventname, Eventdate)
values ('Universal declaration of Human Rights', '12/10/1948')
insert into tbl_historicalEvents (Eventname, Eventdate)
values ('Birthday of Johan Sebastian Bach', '03/21/1685')

Page 7 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
Note: You will now notice that the last insert runs successfully because of the date
datatype.
6. Close SQL Server a. Close SQL Server Management Studio without saving changes.
Management Studio

Page 8 of 13
Working with the new DATE datatype in SQL Server 2008

Exercise 3
Modifying T-SQL to benefit from the date datatype

Scenario
In this exercise you will modify an existing function to benefit from the date datatype range provided in SQL Server
2008.

You have a user-defined table valued function that calculates the interest value over a certain period in time starting
from the current date. The procedure excepts 3 parameters: Amount, Percentage, Years and returns a table that
shows you the amount of interest and the total amount including the interest value over the period of Years, starting
from the current date.

Tasks Detailed Steps


Complete the following 8 a. Click Start | All Programs | Microsoft SQL Server code name Katmai | SQL
tasks on: Server Management Studio menu.
b. Click ‘Connect’ in the “Connect to Server” dialog box after ensuring the
SQL2008CTP following settings:
• Server type: Database Engine
1. Start SQL Server • Server name: SQL2K8
Management Studio
• Authentication: Windows Authentication
Note: You may need to change the server name if required.
2. Open a .sql script Note: Information - It is very common that when working with date data, the mistake
that contains the is made by choosing the wrong datatype in a database design. In this example we will
definition of the purposely implement the wrong datatype, and then take corrective action
current function
a. Click on ‘File | Open | File’ in the standard toolbar.
b. Browse to the SQL 2008 HOL ShortCut on the desktop and open the
CreateFunction.SQL script in the Date Time Data Folder. The following
content will display:

USE LABDB
GO
CREATE FUNCTION UDF_CALCULATE_INTEREST
(@Amount decimal (9,2), @Percentage decimal (9,2),
@Years int)
RETURNS
@tbl_InterestCalculation
TABLE (Startdate smalldatetime, Amount decimal (9,2),
Percentage Decimal(9,2), TotalAmountByYearEnd decimal(9,2), InterestAmount
decimal (9,2),
YearCounter int, EndDate smalldatetime)
as
begin
declare @loop tinyint

Page 9 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
declare @TotalAmountByYearEnd decimal (9,2)
declare @StartDate datetime
declare @Enddate datetime
set @StartDate = getdate()
set @TotalAmountbyYearEnd = 0
set @loop = 0
while @loop < @Years
begin
set @loop = @loop + 1
set @TotalAmountByYearEnd =
@Amount + (@Amount * @percentage)
set @Enddate = Dateadd(year,1,@Startdate)
insert into @tbl_InterestCalculation
values (@StartDate,@Amount,
@percentage,@TotalAmountByYearEnd,
@TotalAmountByYearEnd -
@Amount,@loop,@Enddate)
set @startdate = @Enddate
set @Amount = @TotalAmountByYearEnd
end
return
end

c. Execute the Create Function statement by clicking ‘Execute’ on the standard


toolbar or by pressing ‘F5’
3. Use the function to a. In the same query window, delete the previous statement(s).
calculate the interest b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
for a certain amount
by pressing ‘F5’

select * from dbo.UDF_CALCULATE_INTEREST (500,0.01,20)

The query result will look similar to:

4. Rerun the query with a. In the same query window, delete the previous statement(s).
out of scope values b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
by pressing ‘F5’

Page 10 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps

select * from dbo.UDF_CALCULATE_INTEREST (500,0.01,80)

You will receive the following error message:


Msg 242, Level 16, State 3, Line 17
The conversion of a datetime data type to a smalldatetime data type resulted in
an out-of-range value.

Note: This error occurs because the smalldatetime variable used in the function would
not allow the data conversion going to a data post 2079.
5. Modify the function Note: Information - By modifying the function to a date datatype you will address the
to apply the new date date conversion issues you had in the previous call to the function.
datatype
a. Click on ‘File | Open | File’ in the standard toolbar.
b. Browse to the SQL 2008 HOL ShortCut on the desktop and open the
CreateFunction.SQL script in the Date Time Data Folder. The following
content will display:

USE LABDB
GO
CREATE FUNCTION UDF_CALCULATE_INTEREST
(@Amount decimal (9,2), @Percentage decimal (9,2),
@Years int)
RETURNS
@tbl_InterestCalculation
TABLE (Startdate smalldatetime, Amount decimal (9,2),
Percentage Decimal(9,2), TotalAmountByYearEnd decimal(9,2), InterestAmount
decimal (9,2),
YearCounter int, EndDate smalldatetime)
as
begin
declare @loop tinyint
declare @TotalAmountByYearEnd decimal (9,2)
declare @StartDate datetime
declare @Enddate datetime
set @StartDate = getdate()
set @TotalAmountbyYearEnd = 0
set @loop = 0
while @loop < @Years
begin
set @loop = @loop + 1
set @TotalAmountByYearEnd =
@Amount + (@Amount * @percentage)
set @Enddate = Dateadd(year,1,@Startdate)
insert into @tbl_InterestCalculation
values (@StartDate,@Amount,
@percentage,@TotalAmountByYearEnd,
@TotalAmountByYearEnd -

Page 11 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
@Amount,@loop,@Enddate)
set @startdate = @Enddate
set @Amount = @TotalAmountByYearEnd
end
return
end

c. Modify the code to replace the smalldatetime and datetime variable declarations
by a date datatype and replace the create statement with an ALTER FUNCTION
statement. The code should display as listed:

USE LABDB
GO
ALTER FUNCTION UDF_CALCULATE_INTEREST
(@Amount decimal (9,2), @Percentage decimal (9,2),
@Years int)
RETURNS
@tbl_InterestCalculation
TABLE (Startdate DATE, Amount decimal (9,2),
Percentage Decimal(9,2), TotalAmountByYearEnd decimal(9,2), InterestAmount
decimal (9,2),
YearCounter int, EndDate DATE)
as
begin
declare @loop tinyint
declare @TotalAmountByYearEnd decimal (9,2)
declare @StartDate DATE
declare @Enddate DATE
set @StartDate = getdate()
set @TotalAmountbyYearEnd = 0
set @loop = 0
while @loop < @Years
begin
set @loop = @loop + 1
set @TotalAmountByYearEnd =
@Amount + (@Amount * @percentage)
set @Enddate = Dateadd(year,1,@Startdate)
insert into @tbl_InterestCalculation
values (@StartDate,@Amount,
@percentage,@TotalAmountByYearEnd,
@TotalAmountByYearEnd -
@Amount,@loop,@Enddate)
set @startdate = @Enddate
set @Amount = @TotalAmountByYearEnd
end
return
end
d. Execute the Create Function statement by clicking ‘Execute’ on the standard

Page 12 of 13
Working with the new DATE datatype in SQL Server 2008
Tasks Detailed Steps
toolbar or by pressing ‘F5’
6. Re-Run the query a. In the same query window, delete the previous statement(s).
with the previous out b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
of scope values
by pressing ‘F5’

select * from dbo.UDF_CALCULATE_INTEREST (500,0.01,80)

The query will now execute successfully and display the result set for a period of
80 years.
7. You will display the a. In the same query window, delete the previous statement(s).
result if you would b. Run the following statement(s) by clicking ‘Execute’ on the standard toolbar or
invest $2000 over a
by pressing ‘F5’
period of 100 years
with an interest rate
of 1 percent select * from dbo.UDF_CALCULATE_INTEREST (500,0.01,100)
where YearCounter = 100

The query result will look similar to:

8. Close SQL Server a. Close SQL Server Management Studio without saving changes.
Management Studio

Page 13 of 13