I have a table with a lot of employees, let's say 'Employees' table. This table have a date column among others. Let's say this column is called, 'InjuryDate'.
I would like to select all the employees that satisfy below conditions:
- InjuryDate is within current month, for example, if current month is July, I want all employees that: InjuryDate >= 01/07/2017 and InjuryDate <= 31/07/2017.
- InjuryDate is between day 20 of the past month and the first day of the current month. For example, if current month is July, I want all employees that: InjuryDate >= 20/06/2017 and InjuryDate < 01/07/2017.
So taken into account what is said here (Taken into account that SQL Server can use an index on the column, if appropriate), I 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 as varchar(255)) as date)
SELECT *
FROM Employees
WHERE (
-- Condition 1
InjuryDate >= cast(@today - day(@today) + 1 as date)
AND
InjuryDate < dateadd(month, 1, cast(@today - day(@today) + 1 as date) )
)
OR
(
-- Condition 2
InjuryDate >= @EarlyDate
AND
InjuryDate < cast(@today - day(@today) + 1 as date)
)
Is it correct, or is there any other better way to do it?
I am using SQL Server 2008.