SQL Server: Return all rows of a table which date field satisfies some date conditions -
i have table lot of employees, let's 'employees' table. table have date column among others. let's column called, 'injurydate'.
i select employees satisfy below conditions:
- injurydate within current month, example, if current month july, want employees that: injurydate >= 01/07/2017 , injurydate <= 31/07/2017.
- injurydate between day 20 of past month , first day of current month. example, if current month july, want employees that: injurydate >= 20/06/2017 , injurydate < 01/07/2017.
so taken account said here (taken account sql server can use index on column, if appropriate), have done below query:
declare @today datetime = getdate() declare @day int = 20 declare @month int = month(dateadd(month, -1, @today)) declare @year int = year(dateadd(month, -1, @today)) declare @earlydate datetime = cast(cast(@year*10000 + @month*100 + @day varchar(255)) date) select * employees ( -- condition 1 injurydate >= cast(@today - day(@today) + 1 date) , injurydate < dateadd(month, 1, cast(@today - day(@today) + 1 date) ) ) or ( -- condition 2 injurydate >= @earlydate , injurydate < cast(@today - day(@today) + 1 date) )
is correct, or there other better way it?
i using sql server 2008.
try this:
declare @today date = getdate(); declare @todayday int = datepart(day, @today); declare @earlydate date = dateadd(day, 19, dateadd(month, datediff(month, 0, @today) - 1, 0)); declare @nextmonthfirstdaydate date = dateadd(month, datediff(month, 0, @today) + 1, 0); select * ( values (1, '2017-06-19'), (2, '2017-06-20'), (3, '2017-07-19'), (4, '2017-07-31'), (5, '2017-08-01') ) employees(id,injurydate) injurydate >= @earlydate , injurydate < @nextmonthfirstdaydate;
output:
id injurydate ----------- ---------- 2 2017-06-20 3 2017-07-19 4 2017-07-31
Comments
Post a Comment