r/SQL • u/fatandgeared8675309 • May 03 '22
MS SQL Reoccurring query, no hard coding, MS SQL
I am looking for a WHERE clause to set a reoccurring query to be run for the past 2 weeks. No hard coding can be used. Anyone have any ideas?
Have tried “>= getdate() -14 “ and that’s not pulling how I want. Any suggestions help.
1
Upvotes
1
u/PossiblePreparation May 03 '22
Getdate()-14should return 14 days ago. Maybe some sample data and an explanation of what you want to see would help. Make sure you include the full attempt1
u/killagoose May 03 '22
It is hard to say without seeing your query and the dataset. My shot in the dark would be to use
>= CAST(DATEADD(DD, -14, GETDATE()) AS DATE)This will return a rolling date, no time, of 14 days in the past.
1
u/r3pr0b8 GROUP_CONCAT is da bomb May 03 '22
the real problem lies in the definition of "past 2 weeks" which suggests a 14-day period
but is this complete Sunday-Saturday weeks, like on a corporate fiscal calendar? so if today is May 3, is this 14 day period April 17-30? and tomorrow it'll still be those 2 weeks? until next Sunday?
or something else?
1
u/alinroc SQL Server DBA May 03 '22
You cannot accurately/reliably/safely do integer math on a
datetime. Usedateadd(day, -14,getdate())instead. But that will give you 14 days ago from this instant, which will miss earlier parts of the full day that's 14 days ago. IOW, say what you mean, and mean what you say - you might need to do a different calculation.1
u/DonJuanDoja May 03 '22
Really depends, there's a bunch of ways to do it all depending on requirements. Everything from business days to what days you need to run it on and which date ranges need to be included.
Usually it's some combination of SQL Date functions like DATEADD(), DATEPART(), and even custom functions that count business days which also have their own dependencies and requirements.
Also remember that GETDATE includes time so that can actually exclude certain results unless you convert or cast it first.