Question[SQL]:时间精度与时间区间
在SQL2000/2005中datetime类型的时间精度为千分之3秒(3.33毫秒),所以在计算以日期或时间的区间进经常会出现问题,例如以下例子:
Question:计算某天或连续几天内的出货资料。
Answer:
USE tempdb
GO
if OBJECT_ID('TabTest') is not null
drop table TabTest
CREATE TABLE TabTest(
[出貨日期] [datetime] NOT NULL)
GO
SET NOCOUNT ON
INSERT INTO TabTest VALUES('2008-01-13 00:00:00.000')
INSERT INTO TabTest VALUES('2008-01-23 08:08:08.000')
INSERT INTO TabTest VALUES('2008-01-31 00:00:00.000')
INSERT INTO TabTest VALUES('2008-02-05 00:00:00.000')
INSERT INTO TabTest VALUES('2008-02-05 23:59:00.997')
INSERT INTO TabTest VALUES('2008-02-06 00:00:00.000')
INSERT INTO TabTest VALUES('2008-03-08 21:55:00.997')
INSERT INTO TabTest VALUES('2008-03-14 23:59:00.997')
INSERT INTO TabTest VALUES('2008-03-16 10:00:00.000')
INSERT INTO TabTest VALUES('2008-03-28 18:58:00.000')
--select * from TabTest
--解法一:
-- convert(varchar(10),[出貨日期],111) 取出样式"2008/01/13"
-- 替换"/"号 replace(datetime,'/','') 20080113
select * from TabTest where replace(convert(varchar(10),[出貨日期],111),'/','') between '20080205' and '20080205'
--解法二:注意SQL的datetime时间精确度为"一千分之三秒"
select * from TabTest where [出貨日期] between '20080205 00:00:00.000' and '20080205 23:59:59.997'
drop table TabTest
GO
if OBJECT_ID('TabTest') is not null
drop table TabTest
CREATE TABLE TabTest(
[出貨日期] [datetime] NOT NULL)
GO
SET NOCOUNT ON
INSERT INTO TabTest VALUES('2008-01-13 00:00:00.000')
INSERT INTO TabTest VALUES('2008-01-23 08:08:08.000')
INSERT INTO TabTest VALUES('2008-01-31 00:00:00.000')
INSERT INTO TabTest VALUES('2008-02-05 00:00:00.000')
INSERT INTO TabTest VALUES('2008-02-05 23:59:00.997')
INSERT INTO TabTest VALUES('2008-02-06 00:00:00.000')
INSERT INTO TabTest VALUES('2008-03-08 21:55:00.997')
INSERT INTO TabTest VALUES('2008-03-14 23:59:00.997')
INSERT INTO TabTest VALUES('2008-03-16 10:00:00.000')
INSERT INTO TabTest VALUES('2008-03-28 18:58:00.000')
--select * from TabTest
--解法一:
-- convert(varchar(10),[出貨日期],111) 取出样式"2008/01/13"
-- 替换"/"号 replace(datetime,'/','') 20080113
select * from TabTest where replace(convert(varchar(10),[出貨日期],111),'/','') between '20080205' and '20080205'
--解法二:注意SQL的datetime时间精确度为"一千分之三秒"
select * from TabTest where [出貨日期] between '20080205 00:00:00.000' and '20080205 23:59:59.997'
drop table TabTest
SQL2008对时间的支持有了很大的改进,请参考这篇文章<<SQL Server 2008中的新日期数据类型>>
DateTime
SmallDateTime
Datetime2
DatetimeOffset