SQL Server: explanation needed to understand combination of DATEADD and DATEDIFF - sql

I am pretty new to SQL and use the following lines within a Select in order to get the first and last Monday of October (#selYear defines the year).
Can someone here tell me how to adjust this so that it returns the second, third and fourth Monday of October + provide me an explanation so that I can modify this further for other dates ?
Do I just have to change the last 0 in the first formula to 7, 14 or 21 in order to add the additional weeks ?
And if instead of Monday I want Friday or Thursday would I then just replace the 6 by 4 or 3 ?
--1st Monday in October
DATEADD(d, DATEDIFF(d, 0, DATEADD(m, 10-1, DATEADD(yy, DATEDIFF(yy, 0, #selYear), 6)))/7*7, 0),
--last Monday in October
DATEADD(d, DATEDIFF(d, 0, DATEADD(m, 10, DATEADD(yy, DATEDIFF(yy, 0, #selYear), 6)))/7*7, -7),
Edit: #selYear in my case is defined as #selYear nvarchar(4) and the table column I am inserting this into is formatted as datetime - maybe this is wrong as the result should always be a valid date ?
Many thanks in advance, Mike.

declare #date as date = '20141001' -- this is for october 2014
declare #n as int = 0
while (#n<7)
begin
if ((select DATENAME(dw,#date)) = 'Monday') -- write which day you want as pivot
break
else
begin
set #n = #n+1
set #date = DATEADD(D,1,#date)
end
end
select #date first
, DATEADD(D,7,#date) second
, DATEADD(D,14,#date) third
, DATEADD(D,21,#date) fourth

Related

sql server 2008 find next friday or last day of month [duplicate]

This question already has answers here:
SQL . The SP or function should calculate the next date for friday
(4 answers)
Closed 9 years ago.
Using SQL Server 2008
Based on a specified date, I need to find the date of either the next Friday or the last day of the month if the next Friday is in the next month. Would prefer inline SQL as opposed to a Function but will take what I can get.
Examples:
For the month of October 2013:
A date of 10/3/2013 would return 10/4/2013 (the next Friday)
A date of 10/14/2013 would return 10/18/2013 (the next Friday)
A date of 10/25/2013 would return 10/25/2013 (it is a Friday)
A date of 10/29/2013 would return 10/31/2013 (the last day of the month since the next Friday is in the next month)
I'm not an expert in SQL server, but this should get you close. Put this in a SQL Function:
DECLARE #date DATETIME = '10/03/2013';
SELECT MIN(Date) AS NextFridayOrEoMonth
FROM ( SELECT DATEADD(DAY, ( CASE DATEPART(DW, #date)
WHEN 7 THEN 6
ELSE 6 - DATEPART(DW, #date)
END ), #date) AS Date
UNION
SELECT DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, #date) + 1, 0)) AS Date
) AS dates;
EDIT: Actually, here it is as a function. Good luck!
CREATE FUNCTION dbo.NextFridayOrEoMonth ( #date DATETIME )
RETURNS DATETIME
WITH SCHEMABINDING,
RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE #result DATETIME;
SELECT #result = MIN(Date)
FROM ( SELECT DATEADD(DAY, ( CASE DATEPART(DW, #date)
WHEN 7 THEN 6
ELSE 6 - DATEPART(DW, #date)
END ), #date) AS Date
UNION
SELECT DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, #date) + 1, 0)) AS Date
) AS dates;
RETURN #result;
END
GO
SELECT dbo.NextFridayOrEoMonth('10/3/2013') AS NextFridayOrEoMonth; -- 2013-10-04
SELECT dbo.NextFridayOrEoMonth('10/5/2013') AS NextFridayOrEoMonth; -- 2013-10-11
SELECT dbo.NextFridayOrEoMonth('10/14/2013') AS NextFridayOrEoMonth; -- 2013-10-18
SELECT dbo.NextFridayOrEoMonth('10/25/2013') AS NextFridayOrEoMonth; -- 2013-10-25
SELECT dbo.NextFridayOrEoMonth('10/26/2013') AS NextFridayOrEoMonth; -- 2013-10-31
SELECT dbo.NextFridayOrEoMonth('10/29/2013') AS NextFridayOrEoMonth; -- 2013-10-31
GO
Note: Code reviews / comments appreciated.

Specific day of current month and year

I have problem with return of specific day of current month and year. I need for example 15th day. Until now I used in FB/IB existing function:
IB_EncodeDate(EXTRACT(YEAR FROM Current_Date),EXTRACT(Month FROM Current_Date),15)
Does it exist a simply way to convert this for MSSQL database?
edit. I need output in OLE format (41,348 by example) to compare date with another date. I compare date from database with 15th day of current month.
For the 15th day of current month:
SELECT DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0));
To get the silly OLE representation based on this "magic" date, 1899-12-30:
SELECT DATEDIFF(DAY, -2, DATEADD(DAY, 14,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)));
Answer (on March 11th, when I updated this answer for the changed requirement):
-----
41348
So, you have a date, and want to return the 15th day of the same month?. Well, assuming SQL Server 2008, you could do this:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
For Previous versions of SQL Server:
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
This seems like a quick answer.
declare #OLEDate int
declare #currentDate as datetime
set #currentDate = DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
set #OLEDate = convert(float, #currentdate)
-- PRINT #OLEDate
based on Aaron Bertrand's answer and your need for the integer conversion
To get 10th day of current day
declare #cur_month int,#cur_yr int,#tenth_dt date
set #cur_month=month(getdate())
set #cur_yr=YEAR(getdate())
set #tenth_dt=convert(date,'10/'+convert(varchar(5),#cur_month)+'/'+convert(varchar(5),#cur_yr),103)
select #tenth_dt
Not sure if you after Day or Date. This gives both dayOfWeek and specificDate for any culture
declare #myDay int = 15
select convert(date,myday) specificDate, datename(dw,myday) dayOfWeek
from (
select convert(varchar(6),getdate(),112) + convert(varchar, #myDay) myday
) x
Fiddle Demo Here
| SPECIFICDATE | DAYOFWEEK |
----------------------------
| 2013-02-15 | Friday |
Current_Date in SQL Server would be getdate().
To get the 15th day in OLE Automation format, try:
select datediff(day, '18991230', dateadd(day, -day(getdate()) + 15, getdate()))
A bit more straightforward approach:
CAST(FORMAT(GETDATE(), 'yyyy-MM-15') AS DateTime)

How to get Previous business day in a week with that of current Business Day using sql server

i have an ssis Package which runs on business days (mon-Fri). if i receive file on tuesday , background(DB), it takes previous business day date and does some transactions. If i run the job on friday, it has to fetch mondays date and process the transactions.
i have used the below query to get previous business date
Select Convert(varchar(50), Position_ID) as Position_ID,
TransAmount_Base,
Insert_Date as InsertDate
from tblsample
Where AsOfdate = Dateadd(dd, -1, Convert(datetime, Convert(varchar(10), '03/28/2012', 101), 120))
Order By Position_ID
if i execute this query i'll get the results of yesterdays Transactios. if i ran the same query on monday, it has to fetch the Fridays transactions instead of Sundays.
SELECT DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
WHEN 'Sunday' THEN -2
WHEN 'Monday' THEN -3
ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
I prefer to use DATENAME for things like this over DATEPART as it removes the need for Setting DATEFIRST And ensures that variations on time/date settings on local machines do not affect the results. Finally DATEDIFF(DAY, 0, GETDATE()) will remove the time part of GETDATE() removing the need to convert to varchar (much slower).
EDIT (almost 2 years on)
This answer was very early in my SO career and it annoys me everytime it gets upvoted because I no longer agree with the sentiment of using DATENAME.
A much more rubust solution would be:
SELECT DATEADD(DAY, CASE (DATEPART(WEEKDAY, GETDATE()) + ##DATEFIRST) % 7
WHEN 1 THEN -2
WHEN 2 THEN -3
ELSE -1
END, DATEDIFF(DAY, 0, GETDATE()));
This will work for all language and DATEFIRST settings.
This function returns last working day and takes into account holidays and weekends. You will need to create a simple holiday table.
-- =============================================
-- Author: Dale Kilian
-- Create date: 2019-04-29
-- Description: recursive function returns last work day for weekends and
-- holidays
-- =============================================
ALTER FUNCTION dbo.fnGetWorkWeekday
(
#theDate DATE
)
RETURNS DATE
AS
BEGIN
DECLARE #importDate DATE = #theDate
DECLARE #returnDate DATE
--Holidays
IF EXISTS(SELECT 1 FROM dbo.Holidays WHERE isDeleted = 0 AND #theDate = Holiday_Date)
BEGIN
SET #importDate = DATEADD(DAY,-1,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
--Satruday
IF(DATEPART(WEEKDAY,#theDate) = 7)
BEGIN
SET #importDate = DATEADD(DAY,-1,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
--Sunday
IF(DATEPART(WEEKDAY,#theDate) = 1)
BEGIN
SET #importDate = DATEADD(DAY,-2,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
RETURN #importDate;
END
GO
Then how about:
declare #dt datetime='1 dec 2012'
select case when 8-##DATEFIRST=DATEPART(dw,#dt)
then DATEADD(d,-2,#dt)
when (9-##DATEFIRST)%7=DATEPART(dw,#dt)%7
then DATEADD(d,-3,#dt)
else DATEADD(d,-1,#dt)
end
The simplest solution to find the previous business day is to use a calendar table with a column called IsBusinessDay or something similar. The your query is something like this:
select max(BaseDate)
from dbo.Calendar c
where c.IsBusinessDay = 0x1 and c.BaseDate < #InputDate
The problem with using functions is that when (not if) you have to create exceptions for any reason (national holidays etc.) the code quickly becomes unmaintainable; with the table, you just UPDATE a single value. A table also makes it much easier to answer questions like "how many business days are there between dates X and Y", which are quite common in reporting tasks.
You can easily make this a function call, adding a second param to replace GetDate() with whatever date you wanted.
It will work for any day of the week, at any date range, if you change GetDate().
It will not change the date if the day of week is the input date (GetDate())
Declare #DayOfWeek As Integer = 2 -- Monday
Select DateAdd(Day, ((DatePart(dw,GetDate()) + (7 - #DayOfWeek)) * -1) % 7, Convert(Date,GetDate()))
More elegant:
select DATEADD(DAY,
CASE when datepart (dw,Getdate()) < 3 then datepart (dw,Getdate()) * -1 + -1 ELSE -1 END,
cast(GETDATE() as date))
select
dateadd(dd,
case DATEPART(dw, getdate())
when 1
then -2
when 2
then -3
else -1
end, GETDATE())
thanks for the tips above, I had a slight variant on the query in that my user needed all values for the previous business date. For example, today is a Monday so he needs everything between last Friday at midnight through to Saturday at Midnight. I did this using a combo of the above, and "between", just if anyone is interested. I'm not a massive techie.
-- Declare a variable for the start and end dates.
declare #StartDate as datetime
declare #EndDate as datetime
SELECT #StartDate = DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
WHEN 'Sunday' THEN -2
WHEN 'Monday' THEN -3
ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
select #EndDate = #StartDate + 1
select #StartDate , #EndDate
-- Later on in the query use "between"
and mydate between #StartDate and #EndDate

SQL query to find last day of current month?

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
Hi everyone I have a query to find the last day of current month, which is surely working well, but I am unable to understand it, because I have other similar requirements and have to change it accordingly.
Can somebody explain it to me..
Thanks in advance
Get the DateTime of Now
GETDATE() -- 2011-09-15 13:45:00.923
Calculate the difference in month's from '1900-01-01'
DATEDIFF(m, 0, GETDATE()) -- 1340
Add the difference to '1900-01-01' plus one extra month
DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0) -- 2011-10-01 00:00:00.000
Remove one second
DATEADD(s, -1, DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0)) -- 2011-09-30 23:59:59.000
This will give you the last day of current month but ignores time
select EOMONTH(GETDATE())
From Microsoft tech net
CREATE FUNCTION EOMONTH
(
#date datetime,
#months int
)
RETURNS datetime
AS
BEGIN
declare #eom datetime
declare #d datetime
set #d = dateadd(MONTH, #months, #date)
select #eom = dateadd(SECOND,-1,DATEADD(MONTH,datediff(MONTH,0,#d)+1,0))
RETURN #eom
END
GO
SELECT DATEPART (DD,EOMONTH(GETDATE())) AS 'the last day of the Current month'
Here DATEPART function is used to print the integer part of day.. if the the name of day is asked then we have to use DATENAME() function.
In query, last day means end of the month so we used EOMONTH() function.
GETDATE() is to represent current month.

Get first Sunday of next month using T-SQL

Looking for a way to get the date in the format "11/1/2009", which would be the first sunday of next month. I want to run this query after the first sunday in october to get the first sunday of the upcoming month. What is the best method to accomplish this with a T-SQL query?
Thanks
try this:
Declare #D Datetime
Set #D = [Some date for which you want the following months' first sunday]
Select DateAdd(day, (8-DatePart(weekday,
DateAdd(Month, 1+DateDiff(Month, 0, #D), 0)))%7,
DateAdd(Month, 1+DateDiff(Month, 0, #D), 0))
EDIT Notes:
The first of next Month is given by the expression:
DateAdd(Month, 1+DateDiff(Month, 0, #D), 0)
or by:
which can be modified to give the first of the month two months from now by changing the 1 to a 2:
DateAdd(Month, 2+DateDiff(Month, 0, #D), 0)
EDIT: In response to #NissanFan, and #Anthony: to modify this to return the first Monday Tuesday Wednesday, etc, change the value 8 to a 9, 10, 11, etc....
Declare #Sun TinyInt Set #Sun = 8
Declare #Mon TinyInt Set #Mon = 9
Declare #Tue TinyInt Set #Tue = 10
Declare #Wed TinyInt Set #Wed = 11
Declare #Thu TinyInt Set #Thu = 12
Declare #Fri TinyInt Set #Fri = 13
Declare #Sat TinyInt Set #Sat = 14
Declare #D Datetime, #FONM DateTime -- FirstofNextMonth
Set #D = [Some date for which you want the following months' first sunday]
Set #FONM = DateAdd(Month, 1+DateDiff(Month, 0, #D),0)
Select
DateAdd(day, (#Sun -DatePart(weekday, #FONM))%7, #FONM) firstSunInNextMonth,
DateAdd(day, (#Mon -DatePart(weekday, #FONM))%7, #FONM) firstMonInNextMonth,
DateAdd(day, (#Tue -DatePart(weekday, #FONM))%7, #FONM) firstTueInNextMonth,
DateAdd(day, (#Wed -DatePart(weekday, #FONM))%7, #FONM) firstWedInNextMonth,
DateAdd(day, (#Thu -DatePart(weekday, #FONM))%7, #FONM) firstThuInNextMonth,
DateAdd(day, (#Fri -DatePart(weekday, #FONM))%7, #FONM) firstFriInNextMonth,
DateAdd(day, (#Sat -DatePart(weekday, #FONM))%7, #FONM) firstSatInNextMonth
Just an FYI rather then coming up with some code to do this how about using a calendar table.
Take a look at this: http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html
This also may help:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=99696
Here is a query to get first working day of next month
DECLARE #DAYOFWEEK INT,#ReminderDate DateTime
SET #DAYOFWEEK = DATEPART( WEEKDAY,DateAdd(D,- Day(GetDate())+1, DATEADD(M,1,GetDate())) )
Print #DAYOFWEEK
If #DAYOFWEEK = 1
Set #ReminderDate = DateAdd(D,- Day(GetDate())+2, DATEADD(M,1,GetDate()))
Else If #DAYOFWEEK =7
Set #ReminderDate = DateAdd(D,- Day(GetDate())+3, DATEADD(M,1,GetDate()))
Else
Set #ReminderDate = DateAdd(D,- Day(GetDate())+1, DATEADD(M,1,GetDate()))
Print #ReminderDate
Reference taken from this blog:
SQL Server 2012 introduced one new TSQL EOMONTH to return the last day of the month that contains the specified date with an optional offset.
CREATE TABLE tbl_Test_EOMONTH
(
SampleDate DATETIME
)
GO
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-12-20')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-11-08')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-10-16')
INSERT INTO tbl_Test_EOMONTH VALUES ('2015-09-26')
INSERT INTO tbl_Test_EOMONTH VALUES ('2016-01-31')
GO
SELECT
DATEADD(DAY,8-DATEPART(WEEKDAY,DATEADD(DAY,0,EOMONTH([SampleDate])))
,EOMONTH([SampleDate])) AS FirstSunday_ofTheNextMonth
FROM tbl_Test_EOMONTH
GO
You can use DATENAME to determine the day you want, I might recommend a loop to move the date from the 01 of the month in question to get to the first sunday.
So lets try:
DECLARE #DateTime DATETIME
Set to the date to start off with, then add 1 day until you find what you are looking for. Use datename with dw...
We have used this to determine weekends, but holidays will be a problem, where we use a table to store that.
Try this code as a function:
-- Variables
DECLARE #DATE DATETIME
DECLARE #DAY INT
DECLARE #DAYOFWEEK INT
DECLARE #TESTDATE DATETIME
-- Set
SET #TESTDATE = GETDATE()
SET #DATE = DATEADD( MONTH, 1, #TESTDATE )
SET #DAY = DATEPART( DAY, #TESTDATE )
SET #DATE = DATEADD( DAY, -#DAY + 1, #DATE )
SET #DAYOFWEEK = DATEPART( WEEKDAY, #DATE )
IF #DAYOFWEEK > 1
BEGIN
SET #DAYOFWEEK = 8 - #DAYOFWEEK
END
ELSE
BEGIN
SET #DAYOFWEEK = 0
END
SET #DATE = DATEADD( DAY, #DAYOFWEEK, #DATE )
-- Display
PRINT #TESTDATE
PRINT #DAY
PRINT #DAYOFWEEK
PRINT #DATE
Here is the non-system specific way to determine the first Sunday of the following month:
First, get the current month and add one month.
Next, set the date of that variable to be on the first.
Next, find the day value of that date (let's assume Mondays are 1 and Sundays are 7).
Next, subtract the day value of the 1st of the month from the day value of Sunday (7).
You now have the number of days between the first of the month and the first Sunday. You could then add that to the date variable to get the first Sunday, or, since we know the first of the month is 1, you could just add one to the difference (found in that last step above) and that is the date of the first Sunday. (You have to add one because it's subtracting and thus if the first of the given month IS Sunday, you'd end up with 0).
I have been looking through the T-SQL documentation and it is not at all intuitive as to how how you would use my method, but you will need the concept of "day of week number" to make it work no matter what.
This would be simplest with an auxiliary calendar table. See this link, for example.
However, it can be done without one, though it's rather tricky. Here I assume you want the first future date that is the first Sunday of a month. I've written this with a variable #now for - well - now, so it's easier to test. It might be possible to write more simply, but I think this has a better chance of being correct than quickly-written simpler solutions. [Corrected by adding DAY(d) < 8]
SET #now = GETDATE();
WITH Seven(i) AS (
SELECT -1 UNION ALL SELECT 0 UNION ALL SELECT 1
UNION ALL SELECT 3 UNION ALL SELECT 4
UNION ALL SELECT 5 UNION ALL SELECT 6
), Candidates(d) AS (
SELECT DATEADD(WEEK,i+DATEDIFF(WEEK,'19000107',#now),'19000107')
FROM Seven
)
SELECT TOP (1) d AS SoonestFutureFirstSunday
FROM Candidates
WHERE DAY(d) < 8 AND MONTH(d) >= MONTH(#now)
AND (MONTH(d) > MONTH(#now) OR DAY(d) > DAY(#now))
ORDER BY d; ORDER BY d;
I reckon that the answer is this
SELECT DATEADD(Month, DATEDIFF(Month, 0, GETDATE()) + 1, 0) + 6 - (DATEPART(Weekday,
DATEADD(Month,
DATEDIFF(Month,0, GETDATE()) + 1, 0))
+ ##DateFirst + 5) % 7 --FIRST sunday of following month