开发者

T-SQL - get value between two dates

I just watched such an example which shows how to get all cols by date here it is...

DECLARE @MyGetDate DATETIME

SELECT @MyGetDate = '2 Mar 2003 21:40'

SELECT  * 
FROM @Table
WHERE convert(varchar, @MyGe开发者_开发知识库tDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14)

... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is

SELECT  value, my_date_col
FROM myTable
WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14)

But it doesn't work :( So my question is how to use col my_date_col in such kind of statement?

Any useful comment is appreciated


I assume your my_date_col is DateTime column, then you don't need the casting. Casting is needed because the sample uses string representation of dates.

DECLARE @date DATETIME
SET @date = GETDATE()

SELECT value, my_date_col 
FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, @date) AND @date


This should work just fine, assuming my_date_col is a DATETIME:

SELECT  value, my_date_col
FROM myTable
WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate()

If nothing is returned, there are no rows with a my_date_col in the last 50 minutes.


Get rid of the CONVERT statements, you want to compare dates, not varchars.

SELECT  value, my_date_col
FROM myTable
WHERE  my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate(), 14


select value1, date_column from @Table
WHERE date_column between date1 and date2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜