I have a table of rows in MS SQL that contain a start and end day of the week, hour, and time. I need a T-SQL query that can pull rows from that table where GETDATE matches the day of week and time of those rows. Specifically, I need the query to work if a row has a day/time that starts on one day of the week and ends on the next day.
Here's the structure I'm working with:
_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) = 'My Sample Row' _id (int) = 1How would I retrieve this ro开发者_JAVA技巧w given the current DATETIME?
you could try something like:
select * from [yourtable]
where yourdatefield between getDate() and (getDate()+1 )
You should be able to use datepart
function to go with getdate
function:
http://msdn.microsoft.com/en-us/library/aa258265%28v=sql.80%29.aspx
I am still unclear about your requirements as they seem a bit impracticle. But here is my go.
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.
精彩评论