default date value of every Friday in SQL Server? - sql

In SQL Server 2008 i want to set a default date value of every Friday to show up in the column when i insert a new record?
ALTER TABLE myTable ADD CONSTRAINT_NAME DEFAULT GETDATE() FOR myColumn
Whats the best way to show every Friday?
I want the default value to be based on the now date then knowing that the next available date is 05-07/2013
I have the following:
dateadd(d, -((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
But when passing todays date, it gave me: 2013-06-28 which is actually LAST Friday!, it should be the up and coming Friday!

SELECT DATEADD(day,-3, DATEADD(week, DATEDIFF(week, 0, current_timestamp)+1, 0)) AS LastFridayDateOfWeek
Gets the last date of current week (sunday) then subtracts 3 from that to get Friday.
Replace current_timestamp if you need a different dates friday.
EDIT:
I thought about this a bit, and if the above (Friday THIS WEEK, so for Saturday it gives the previous date) does not work, you could easily use a reference date set like so:
DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
Same thing but with no hard coded Friday/Saturday in it:
DATEADD(DAY,7 + DATEDIFF(day,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime),5),#checkDateTime)/7*7,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime), 4))
So for 20100109 is a Friday.
SET #checkDateTime = '2012-01-14 3:34:00.000'
SELECT DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
it returns "2012/1/20"
But for SET #checkDateTime = '2012-01-13 3:34:00.000' it returns "2012/1/13"

If your current query gives you last Friday, the easiest thing to do is simply to add 7 to it:
select dateadd(d, 7-((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
------------------^

SELECT CONVERT(DATE, ( CASE WHEN DATEPART(dw, GETDATE()) - 6 <= 0
THEN DATEADD(dd,
( DATEPART(dw, GETDATE()) - 6 ) * -1,
GETDATE())
ELSE DATEADD(dd, ( DATEPART(dw, GETDATE()) ) - 1,
GETDATE())
END )) AS NearestFriday

Just add 7 to the formula
SELECT DATEADD(dd,CAST(5-GETDATE() AS int)%7,GETDATE()+7)
To verify the formula:
WITH test AS (
SELECT GETDATE() AS d UNION ALL
SELECT DATEADD(dd,1,d)
FROM test WHERE d < GETDATE() + 30
)
SELECT
d AS [input],
DATEADD(dd,CAST(5-d AS int)%7,d+7) AS [output]
FROM test
To tweak the the formula, adjust the 5- and the +7

Related

T-SQL Dynamic date range in WHERE clause (Last fiscal year + year to date)

I'm using the following WHERE clause to only load records from the last fiscal year plus a year to date.
Running without the WHERE clause, it takes 30seconds for 1mil records. With the WHERE clause, I had to stop it after 2hours.
Can you please share your thoughts
WHERE
([schema].[table].[DATE] >= DATEADD
(yy, - 1, DATEADD
(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,
CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)
)
)
)
Declare #PastFiscalYear Date
Set #PastFiscalYear= DATEADD(yy, - 1, DATEADD(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)))
WHERE
([schema].[table].[DATE] >= #PastFiscalYear )
Can you try this
This will bring back data since the previous fiscal year start date. Just change the -3 to what ever your FY offset is. -3 is for October.
[schema].[table].[DATE] >= DATEADD(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())), 0))

how can I get last 7 days of data being my date field a number?

I need to get last 7 days data excluding Sunday being my date field a number. How can I do it? Field structure 20140425. For example is I run the statement today it should give me date range between 20140424 - 20140417 excluding 20140420.
The hitch is of course converting the number based date to a real date. This seems to work:
select convert(datetime, convert(char(10), 20140425))
To expand, your query would look like this:
select *
from [Table]
where convert(datetime, convert(char(10), [columnname])) between convert(varchar, getdate() - 8, 101) and convert(varchar, getdate() - 1, 101)
and datepart(DW, convert(datetime, convert(char(10), [columnname]))) <> 1
The convert(varchar, getdate - 1, 101) will return you 12:00am yesterday morning. My first pass didn't include that and would've only given a 6 day range.
SELECT *
FROM Table_Name
WHERE CAST(DateField AS DATE) >= DATEADD(DAY, -7, GETDATE())
AND CAST(DateField AS DATE) <= GETDATE()
AND DATEPART(DW,CAST(DateField AS DATE)) <> 1

Select date range from two tables from present day to first day of that month

Using Microsoft SQL 2008. I have two tables that I want to select from the current date to the first day of that month (or within the same month). Let's say today's date is 05/09/2012 and the date column is 'datecolumn'. Fom the tables below I should only get rowsets 6,7 from table1 and rowsets 9,2 from table 2 because those dates are within the same month as 05/09/2012.
table1
4 02/01/2012
5 01/02/2011
6 05/01/2012
7 05/20/2012
table2
8 02/01/2012
9 05/14/2012
3 01/02/2011
2 05/18/2012
I tried this but it didnt work:
DECLARE #daterange
SET #daterange = (DATEPART(MONTH,GETDATE()) + '/' + DATEPART(YEAR,GETDATE()))
SELECT blah from table where (DATEPART(MONTH,datecolumn) + '/' + DATEPART(YEAR,datecolumn)) = #daterange
You can simplify it, no need to reconstitute the date field from GETDATE():
SELECT blah
FROM table
WHERE DATEPART(MONTH,datecolumn) = DATEPART(MONTH,getdate()) AND
DATEPART(YEAR,datecolumn) = DATEPART(YEAR,getdate())
You can receive the first of the current month like this:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
By adding one month to the above result, you'll receive the first of the next month:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)
Using those two dates, you can retrieve the required rows like this:
SELECT
…
FROM table1
WHERE date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) , 0)
AND date < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)
How about determining the beginning and end of the current month, and then selecting for records between them:
declare #monthBeginning datetime
set #monthBeginning = (select dateadd(dd,-(day(dateadd(mm,1,getdate()))-1),dateadd(mm,0,getdate()))
declare #monthEnd datetime
set #monthEnd = (select dateadd(dd, -day(dateadd(m,1,getdate())), dateadd(m,1,getdate())))
select *
from dateTable
where datecolumn between #monthBeginning and #monthEnd
If you find yourself using month beginning and ending calculations a lot, I'd recommend putting them into scalar functions - the logic is convoluted enough to not want to repeat it.

datename function in sql

I wanted to get the week from the given date, for this I tried with the DATENAME function to get the WEEK like,
Select DateName(WEEK,'2012-03-09')
am getting the output as 10. I want to get the starting date and ending date of this week like, 2012-03-04 to 2012-03-10 Is it possible?
Do something like this:
DECLARE #MyDate Date = '2012-03-09';
-- This gets you the SUNDAY of the week your date falls in...
SELECT DATEADD(DAY, -(DATEPART(WEEKDAY, #MyDate) - 1), #MyDate);
-- This gets you the SATURDAY of the week your date falls in...
SELECT DATEADD(DAY, (7 - DATEPART(WEEKDAY, #MyDate)), #MyDate);
-- This will show the range as a single column
SELECT
CONVERT(NVarChar, DATEADD(DAY, -(DATEPART(WEEKDAY, #MyDate) - 1), #MyDate))
+ ' through ' +
CONVERT(NVarChar, DATEADD(DAY, (7 - DATEPART(WEEKDAY, #MyDate)), #MyDate));
try the following, change getdate to your date
Select
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek,
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek
This does not rely on your default setting of datefirst.
set datefirst 4 -- this row does nothing in this query.
-- It will hurt the queries using datepart though
declare #t table(dt datetime)
insert #t values('2012-03-09 11:12'), ('2012-03-10 11:12'),('2012-03-11 11:12')
-- week from sunday to saturday
Select dateadd(week, datediff(week, 0, dt),-1),
dateadd(week, datediff(week, 0, dt),+5)
from #t

Get the most recent Friday's date SQL

I'm trying to get the most recent Friday in SQL Server 2008.
I have this. It gets the beginning of the week (monday) then subtracts 3 days to get Friday.
declare #recentFriday datetime = DATEADD(ww, DATEDIFF(dd,0,GETDATE()), 0)-3
When this is run during the week, it gets last Friday's date which is correct. But when run on Friday (or Saturday), it still gets last week's date instead of the current week's Friday. I'm about to use if/else conditions but I'm sure there's an easier way.
This works for any input and any setting of DATEFIRST:
dateadd(d, -((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
It works by adjusting the weekday value so that 0 = Friday, simulating Friday as the beginning of the week. Then subtract the weekday value if non-zero to get the most recent Friday.
Edit: Updated to work for any setting of DATEFIRST.
DECLARE #date DATETIME = '20110512' -- Thursday
SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',#date)%7),#date) --20110506
SET #date = '20110513' -- Friday
SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',#date)%7),#date) --20110513
SET #date = '20110514' -- Saturday
SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',#date)%7),#date) --20110513
Calculate the number of days between a known Friday (05 Jan 1900) and the given date
The remainder left from dividing the difference in 1. by 7 will be the days elapsed since the last Friday
Subtract the remainder in 2. from the given date
you can check if the current day of week is friday or greater DATEPART(dw,GETDATE()) and then call (SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)+4) or (SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)-3)
SELECT
CASE WHEN DATEPART(dw,GETDATE()) >= 5 THEN
(SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)+4)
ELSE
(SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)-3)
END
Using a known Friday date (I'll use Jan 7, 2011) as a starting point, you can do this:
DECLARE #d DATETIME
SET #d = '2011-05-13' /* Friday */
SELECT DATEADD(DAY, (DATEDIFF (DAY, '20110107', #d) / 7) * 7, '20110107')
/* Returns 2011-05-13 */
SET #d = '2011-05-12' /* Thursday */
SELECT DATEADD(DAY, (DATEDIFF (DAY, '20110107', #d) / 7) * 7, '20110107')
/* Returns 2011-05-06 */
Just choose a known Friday that's older than any dates you'll be using in your calculations.
SELECT CONVERT(VARCHAR(12),GETDATE()) AS Today,
CASE WHEN (DATEPART(DW,GETDATE())< 7)
THEN CONVERT(VARCHAR(12),(DATEADD(dd,-(DATEPART(DW,GETDATE())+1),GETDATE())))
ELSE CONVERT(VARCHAR(12),(DATEADD(d,- 1,GETDATE())))
END AS [Last Friday]
Here is a completly set oriented way to achive the last Friday:
select Friday from
(
select max(GetDate()) as Friday where datepart(dw, getdate()) = 6
union all
select max((GetDate() - 1)) where datepart(dw, (getdate() - 1)) = 6
union all
select max((GetDate() - 2)) where datepart(dw, (getdate() - 2)) = 6
union all
select max((GetDate() - 3)) where datepart(dw, (getdate() - 3)) = 6
union all
select max((GetDate() - 4)) where datepart(dw, (getdate() - 4)) = 6
union all
select max((GetDate() - 5)) where datepart(dw, (getdate() - 5)) = 6
) x where Friday is not null
The other solutions were not working for my use case.
This works for finding any previous day by replacing 'Sunday' with the day you`re looking for:
DECLARE #myDate DATE = GETDATE()
WHILE DATENAME(WEEKDAY, #myDate) <> 'Sunday'
BEGIN
SET #myDate = DATEADD(DAY, -1, #myDate)
END
This is what I got I hope it helps
DECLARE #UserDate DateTime
SET #UserDate = '2020-09-03'
SELECT DATEADD(day, (6 - datepart(weekday, #UserDate)) , #UserDate)