-2

I am using SQL Server 2014. I have the following query:

Use MyDatabase

select *
from Table1    
where [CreatedOn] between '2019-01-01' and '2019-12-31'

I need to filter by [CreatedOn] so that it excludes all Saturdays and Sundays between the specified dates.

What would be the correct syntax to perform this operation?

Dale K
  • 25,246
  • 15
  • 42
  • 71
user3115933
  • 4,303
  • 15
  • 54
  • 94
  • 1
    What have you researched? What have you tried? – Dale K Sep 14 '20 at 06:15
  • 1
    Does this answer your question? [How do I exclude Weekend days in a SQL Server query?](https://stackoverflow.com/questions/1803987/how-do-i-exclude-weekend-days-in-a-sql-server-query) – Dale K Sep 14 '20 at 06:16

1 Answers1

2
Where [CreatedOn] between '2019-01-01' and '2019-12-31'
  and DATEPART(WEEKDAY,[CreatedOn]) not in (6, 7) 

just be careful, sunday is the first day of the week in some cultures. If that is the case you need to change not in (6, 7) to not in (7, 1)

you can check the first day of the week with SELECT @@DATEFIRST

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • 1
    When I run SELECT @@DATEFIRST, I get 7. So, I guess I will need to use "not in (7,1)". – user3115933 Sep 14 '20 at 06:28
  • @user3115933 `( @@DateFirst + DatePart( weekday, CreatedOn) - 1 ) % 7 + 1` will always return an integer from `1` to `7` with `1` corresponding to Sunday regardless of the setting of `DateFirst` or `Language`. – HABO Sep 14 '20 at 20:37