The trick is to determine how many days are left next Friday from the proposed date. To help, review the whole week and number of days away from next Friday:
Sunday -2
Monday -3
Tuesday 3
Wednesday 2
Thursday 1
Friday 0
Saturday -1
Now you need a formula to return these results. Since Sunday and Monday follow other patterns from other days of the week, two formulas are needed.
Firstly, on Sunday and Monday. It adds 1 to the value of the day of the week, then takes a negative value to apply to the date of addition. For example, Monday has a default value of 2 as the day of the week value. (2 + 1) * -1 = -3. -3 + Monday = Friday.
Tuesday - Saturday uses the same arithmetic: dates return the values of the day of the week 3, 4, 5, 6, and 7. We need dates that add the values 3,2,1,0, -1, respectively. The formula for obtaining it is DW * -1 + 6.
DECLARE @Date AS datetime SET @Date = '3/1/2010' SELECT CASE WHEN DATEPART(dw, @Date) <= 2 THEN DATEADD(d, -1 * (DATEPART(dw, @Date) + 1), @Date) ELSE DATEADD(d, DATEPART(dw, @Date) * -1 + 6, @Date) END AS NearestFriday
source share