2016-01-22 17 views
0

我想要運行一個查詢以恢復發生在輸入日期是時間戳並且表是時間戳的日期之後發生的查詢。我現在面臨的問題是結果正在逐漸被排除在外,所以一些人失蹤了。參閱以下樣品細節如何比較兩個時間戳作爲SQL Server中的日期

示例SQL

Select * 
from table 
where DateTime >= InputDateTime 

樣品表

Row | DateTime 
1 | 2015-01-16 23:12:11 
2 | 2015-01-15 06:12:24 
3 | 2015-01-14 23:12:24 
4 | 2015-01-15 23:12:24 
5 | 2015-01-12 23:12:24 

預期結果如果InputDateTime = 2015年1月15日12時13分24秒

Row | DateTime 
1 | 2015-01-16 23:12:11 
2 | 2015-01-15 06:12:24 
4 | 2015-01-15 23:12:24 

回答

2

如果您只想考慮日期,請刪除時間組件:

where datetime >= cast(getdate() as date) 

courese,你可以爲一個變量或列也這麼做:

where datetime >= cast(@inputdatetime as date) 
0

現在我明白了,你是比較僅基於關閉日期的希望,我改變我的代碼反映一種方式這樣做:

DECLARE @inputDateTime DATETIME = '2015-01-15 12:13:24' 

-- DROP TABLE [#testTable] 
CREATE TABLE [#testTable] 
(
[Row] INT IDENTITY(1,1), 
[DateTime] DATETIME 
) 

INSERT INTO [#testTable] 
    (
    [DateTime] 
    ) 
VALUES 
    ('2015-01-16 23:12:11'), 
    ('2015-01-15 06:12:24'), 
    ('2015-01-14 23:12:24'), 
    ('2015-01-15 23:12:24'), 
    ('2015-01-12 23:12:24') 

SELECT 
    * 
FROM 
    [#testTable] 
WHERE 
    [DateTime] >= CONVERT(DATETIME,FLOOR(CONVERT(FLOAT,@inputDateTime))) 
+0

2015-01-15 12:13:24應該是中午,這是在上午6點後,例如12:13 PM。它的同一天,但如果它是一個時間戳比較將被排除 – user1605665

+0

啊,我明白你的意思,然後截斷你的inputDateTime變量比較: DECLARE @inputDateTime DATETIME ='2015-01-15 12:13 :24' - DROP TABLE [#testTable] CREATE TABLE [#testTable] ( [行] INT IDENTITY(1,1), [DATETIME] DATETIME ) INSERT INTO [#testTable] \t( \t [DateTime] \t) VALUES 0 ('2015-01-16 23:12:11'), \t('2015-01-15 06:12:24'), \t('2015-01-14 23:12:24'), \t( '2015年1月15日23點12分24秒'), \t( '2015-01-12 23點12分24秒') SELECT \t * FROM \t [#testTable] WHERE \t [日期時間]> = CONVERT(DATETIME,FLOOR(CONVERT(FLOAT,@ inputDateTime))) – SQLPhilosopher