SQL Server Query - Selecting values BETWEEN 2 Dates

时间:2015-05-24 21:56:40

标签: sql-server

I am getting some problems in getting one query done.

I have 2 strings which are suppose to store time in this format (HH:mm Ex: Date1 -> '20:20' and Date2 -> '21:20'). I want to get the current time (CONVERT(VARCHAR(5),getdate(),108) -> to get only 'HH:mm') and get all rows that are between the current date.

The idea is: Select * where "getdate() between date1 and date2", this is not a query, only the idea.

Edit:

Time1   Time2
08:20   09:05
09:05   09:50
10:05   10:50
10:50   11:35
11:45   12:30
12:30   13:15
13:35   14:20

Thx for the solutions, I will check them, but one question how can i "fix" the problem when it's 9:05 (for example), I will get both rows/records, I assume i have to go to the seconds right?

1 个答案:

答案 0 :(得分:1)

以下内容根据您的输入字符串(DATETIME)构建两个基于TIME的@TimeStr1 and @TimeStr2DATE,然后从GETDATE()中删除BETWEEN部分。然后,您可以使用DECLARE @CurrentTime DATETIME, @TimeStr1 VARCHAR(12), @TimeStr2 VARCHAR(12), @Time1 DATETIME, @Time2 DATETIME SET @TimeStr1 = '20:20' SET @TimeStr2 = '21:20' SET @Time1 = CAST('1900-01-01 ' + @TimeStr1 AS DATETIME) SET @Time2 = CAST('1900-01-01 ' + @TimeStr2 AS DATETIME) -- The following strips the date from datetime leaving only a time SET @CurrentTime = DateAdd(ss, DateDiff(ss, DateAdd(dd, DateDiff(dd, 0, GetDate()), 0), GetDate()), 0) SELECT * FROM YourTable WHERE @CurrentTime BETWEEN @Time1 AND @Time2 轻松执行查询。

SELECT * FROM YourTable WHERE @CurrentTime > @Time1 AND  @CurrentTime <= @Time2

这适用于所有版本的SQL SERVER。如果您使用的是版本&gt; = 2008,则存在上述更简单的版本。

如果您担心重叠(例如您的“09:05”问题),请使用以下查询,以避免使用&gt;和&lt; =而不是BETWEEN

{{1}}