在sql server中查找介于一天和一周之间的行

时间:2011-02-05 03:50:28

标签: sql-server tsql dayofweek

我在MS SQL中有一个行表,其中包含一周,小时和时间的开始和结束日期。我需要一个T-SQL查询,它可以从该表中提取GETDATE与星期和时间相匹配的行。具体来说,如果一行的日期/时间从一周的某一天开始到第二天结束,我需要查询才能工作。

这是我正在使用的结构:

_start_day_of_week(int)= 5
_start_hour(int)= 15
_start_minute(int)= 30
_end_day_of_week(int)= 6
_end_hour(int)= 2
_end_minute(int)= 30
_title(string)='我的样本行'
_id(int)= 1

如果给定当前的DATETIME,我将如何检索此行?

3 个答案:

答案 0 :(得分:0)

你可以尝试类似的东西:

select * from [yourtable]
where yourdatefield between getDate() and (getDate()+1 )

答案 1 :(得分:0)

您应该可以使用datepart功能来使用getdate功能:

http://msdn.microsoft.com/en-us/library/aa258265%28v=sql.80%29.aspx

答案 2 :(得分:0)

我仍然不清楚你的要求,因为它们似乎有点不切实际。但这是我的去处。

DECLARE @A AS TABLE(
_start_day_of_week int,
_start_hour int,
_start_minute int,
_end_day_of_week int,
_end_hour int,
_end_minute int,
_title varchar(10),
_id int 
)
--Above is temp table for example
INSERT @A
SELECT 5,15,30,6,2,30,'SAMPLE 1', 1 UNION ALL
SELECT 6,15,30,6,17,30,'SAMPLE 2', 2

DECLARE @month int = datepart(month,getdate())
DECLARE @currentDay int = datepart(dw,getdate())
DECLARE @currentHour int = datepart(hour, getdate())
DECLARE @currentMinute int = datepart(minute, getdate())



SELECT * FROM @A --Don't use select *. This is just an example.
WHERE --Where GETDATE matches
_start_day_of_week = @currentDay --The day of week
AND
_start_hour = @currentHour --and time of those rows
AND
_start_minute = @currentMinute
--I have not done any matching against the _end columns as
--your criteria are vague. Should it exclude all days except
--the current day and the currentday+1?
-- But you would use a similar method.