日期部分之间的时间(而不是转换日期)

时间:2011-12-20 12:34:39

标签: sql-server sql-server-2008

有没有办法使用Datepart来选择使用datepart的时间介于12:20和15:50之间的行,因为转换日期对我来说速度非常慢?

3 个答案:

答案 0 :(得分:2)

例如,您可以使用此

DECLARE 
    @min FLOAT = CAST(CAST('19000101 12:20' AS DATETIME) AS FLOAT),
    @max FLOAT = CAST(CAST('19000101 15:50' AS DATETIME) AS FLOAT)

SELECT 
    *
FROM table
WHERE CAST(DateField AS FLOAT) - FLOOR(CAST(DATEFIELD AS FLOAT)) BETWEEN @min AND @max

但这实际上不是解决方案!!!

最好的方法是再引入1个计算列

NewColumn AS DATEPART(HOUR, DateColumn)*100+DATEPART(minute, DateColumn)  

在其上创建索引并在where子句中使用

WHERE NewColumn BETWEEN 1220 AND 1550

答案 1 :(得分:0)

假设同一天的时间段;

...
where cast(fld as time) between '12:20' and '15:50'

答案 2 :(得分:0)

唯一的选择是使用CTE。测试它,它的工作原理。

LH =低小时 HH - 高时 LM - 低分钟 HM =高分钟

;WITH CTE_LH AS 
(
SELECT *  
FROM DateTable 
WHERE (DATEPART(HOUR, DateCol) >= 12)
)
, CTE_HH AS 
(
SELECT *  
FROM CTE_LH 
 WHERE (DATEPART(HOUR,DateCol) <= 15 )
)
,CTE_LM AS 
(
SELECT *  
FROM CTE_HH 
WHERE (DATEPART(MINUTE,DateCol) >= 20 )
)
,CTE_HM AS 
(
SELECT *  
FROM CTE_LM 
WHERE (DATEPART(MINUTE,DateCol) <= 50 )
)
SELECT * FROM CTE_HM;