技术开发 频道

SQL Server 2008使用日期时间数据类型

练习 2:处理日期和时间数据类型

在本练习中,您将看到以前SQL Server版本当中,datetime与smalldatetime数据类型的一些问题,然后您将会采取一些行动来解决这些问题。

点击Start | All Programs | Microsoft SQL Server 2008 | SQL Management Studio  ,启动SQL Server Management Studio。
在Connect to Server对话框中输入下列信息,然后点击 Connect 按钮:

Server type: Database Engine
Server name: (local)
Authentication: Windows Authentication

创建一个数据表来处理数据类型
查看并 选中 下列代码并点击Execute:

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)

查看并 选中 下列代码并点击Execute:

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')

注意: 最后一条语句将会出现如下错误

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

注意: 发生这个错误的主要原因是,您希望插入到datetime数据类型当中的值超出了可以接受的范围 (从01-01-1753 到 9999-12-31)
查看并 选中 下列代码并点击Execute:

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)

查看并 选中 下列代码并点击Execute:

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')

注意: 您现在将发现最后一个INSERT语句将可以正常执行,因为使用了date 数据类型。
关闭所有应用程序并不要保存所有更改。
关闭Virtual PC 并不要保存更改。
 

0
相关文章