2010-11-03 100 views
1

我需要從SQL Server數據庫中選擇落在某個小時之間的所有記錄。讓我舉一個例子:根據ProgramStart和ProgramEnd之間的當前時間選擇記錄

當前時間是上午9:33,並且在數據庫中有許多Program記錄具有ProgramStart和ProgramEnd。日期的一個例子可能是:

| ProgramStart    | ProgramEnd    | ClientID | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 09:00:00.000 | 1900-01-01 10:00:00.000 | 5  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 11:00:00.000 | 1900-01-01 13:00:00.000 | 4  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 12:00:00.000 | 1900-01-01 14:00:00.000 | 5  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 11:00:00.000 | 1900-01-01 13:00:00.000 | 6  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 16:00:00.000 | 1900-01-01 17:00:00.000 | 7  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 16:00:00.000 | 1900-01-01 17:00:00.000 | 5  | 
+--------------------------+-------------------------+----------+ 
| 1900-01-01 17:00:00.000 | 1900-01-01 18:00:00.000 | 4  | 
+--------------------------+-------------------------+----------+ 

我想提取的所有記錄的客戶端5和當前時間是上午9:33

怎樣才能做到這一點與SQL之間。我試過這個,但它不起作用:

SELECT CAST('1900-01-01 09:33:00.000' AS datetime) AS TimeNow, * FROM Programs 
WHERE ClientID = 5 
AND TimeNow BETWEEN '1900-01-01 09:00:00.000' AND '1900-01-01 10:00:00.000' 

任何建議將不勝感激。

非常感謝, 保羅

回答

2
select * 
    from Programs 
    where ClientId = 5 
     and DATEADD(Day, 0-DATEDIFF(Day, 0, GetDate()), GetDate()) between ProgramStart and ProgramEnd 
1

嘗試:

SELECT * 
FROM Programs 
WHERE ClientId = 5 
AND GETDATE() BETWEEN ProgramStart AND ProgramEnd 

更新 我沒有注意到缺乏數據的日期分量。在調用GetDate()之後,你應該看看gbn的答案來清除日期。我不會在這裏複製他的代碼,因爲這看起來不對。 :)

+0

-1。 '1900年11月20日20:10.xx.yyyy' *永遠*在'1900-01-01 09:00:00.000'和'1900-01-01 10:00:00.000'之間?編輯:-1刪除。 – gbn 2010-11-03 19:11:08

+0

是的,沒有注意到,直到我看到其他答案。 – 2010-11-03 19:13:13

2

這反而會從GETDATE刪除日期組件:

DATEADD(day, -DATEDIFF(DAY, 0, GETDATE()), GETDATE()) 

這堵到查詢

SELECT 
    * 
FROM 
    Programs 
WHERE 
    ClientID = 5 
    AND 
    DATEADD(day, -DATEDIFF(DAY, 0, GETDATE()), GETDATE()) 
       BETWEEN ProgramStart AND ProgramEnd 

在2008+你有時間數據類型太多的SQL Server。然而,三投一會就失效和ProgramStart指標ProgramEnd所以它會值得玩的東西,如:第二個

CAST(GETDATE() AS time) BETWEEN CAST(ProgramStart AS time) AND CAST(ProgramEnd AS time) 
CAST(CAST(GETDATE() AS time) AS smalldatetime) BETWEEN ProgramStart AND ProgramEnd 
+0

+1擊敗我56秒。 – 2010-11-03 19:10:45

相關問題