SQL Date - functions - sql-server

>=DateAdd("ww",-9,Date()-Weekday(Date(),0)+1))
I have the above function in some SQL coding that I have inherited and am struggling to work out what it is actually calculating can anyone help?

Consider this SQL with the statement deconstructed into parts.
It was tested in sql-server 12, and uses the GETDATE() instead of the Date() function.
select
GETDATE() as today,
##DATEFIRST as first_day_of_the_week_number,
DATEPART(WEEKDAY,GETDATE()) as current_day_number_of_the_week,
GETDATE()-DATEPART(WEEKDAY,GETDATE()) as previous_saturday,
GETDATE()-DATEPART(WEEKDAY,GETDATE())+1 as previous_sunday,
DATEADD("ww",-9,GETDATE()-DATEPART(WEEKDAY,GETDATE())+1) as previous_sunday_9_weeks_back;
So it would give the sunday of 9 weeks back.
Note that it assumes that ##DATEFIRST equals 7.
If ##DATEFIRST equals 1 then it would return the monday of 9 weeks back.

Related

SQL Server: Making Monday the start of week

I have an issue (and as reading, it's not just me) with SQL server settings for Sunday as first day of week. But my company needs the weeks to cover the period Monday-Sunday. I tried SET DATEFIRST 1, but it doesn't affect the results. A simple example: today is Sunday; when I enter the following code in SQL, it results in week 33, but it should show week 32, and week 33 should start from tomorrow:
SET DATEFIRST 1
Select DatePart(week, getdate());
I changed the language in my login settings to British English, bit it didn't work, as well. Is there some other way to change the settings?
In most of my queries I need to show the results for last week, with a similar where clause:
WHERE Week = (Select DatePart(week, getdate())-1)
If I can't globally change the settings, than how is it possible to transform the upper clause in such a way, so that to show the results from Monday to Sunday? I am an SQL beginner, searched for an answer in the internet, but couldn't adapt my code. Thank you in advance!
Use DATEPART(ISO_WEEK, ...) after setting SET DATEFIRST 1. This should observe ISO week numbering, as documented in DATEPART documentation.

Query all items for the week in SQL

I have a query that selects all items for the given week and sets their date to be the start day of that week. In some cases the query sets an incorrect date value for the given item and I have traced the problem to be in either DATEDIFF or DATEADD functions.
The query is
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, DateTimeValue), 0) AS NewDateTimeValue
Let's take a date March 27 2016 as an example. The DATEDIFF returns value of 6065 and the DATEADD with that value returns March 28 2016.
For the date March 26 2016, the DATEDIFF returns 6064 and the DATEADD March 21, 2016.
To me this sounds like a FirstDayOfWeek issue and that SQL Server thinks Sunday is the first day of a week and thus giving different values for Sunday and for Saturday (March 27, 2016 is Sunday).
I tried to set the first day of the week by
SET DATEFIRST 1
but that didn't make any difference and SQL returned the same results.
So what causes the SQL function to behave like this and any ideas how to fix it?
I found out that DATEDIFF doesn't respect the DATEFIRST setting and always assumes the week starts on Sunday. This is the reason why my sample case works as it works. This question has some suggested workaround: Is it possible to set start of week for T-SQL DATEDIFF function?
This is happening because you are finding the no. of weeks from date 0 to the supplied date. 0 is actually '1900-01-01' which was a Monday. Therefore,DATEDIFF finds the number of completed weeks from this date until the supplied data. Thats why DATEDIFF for March 27 2016 returns 6065 (as it is the end of a week) and March 26 2016 returns 6064 (as it is still not the end of a week).
This is already explained in this link - Get first day of the week

DATEPART(ww,Date) with SET DATEFIRST

I´m using SQL Server 2005
I´m trying to get the week with DatePart(ww,date) function
My code
SELECT datepart(ww,'2012-01-08 00:00:00')
Return 2
But I want ...
Return 1
According with IS0-8601 and this table from this website
YEAR 2012
Week-01 From 2012-1-2 to 2012-1-8
...
Am I wrong?
There is any trick with SET DATEFIRST 1, I´m trying without success.
Thanks for your time
I can´t use ISO_WEEK, because SQL Server 2005 don´t work
Use ISO_WEEK:
SELECT datepart(ISO_WEEK,'2012-01-08 00:00:00')
You can read more about it on MSDN.
Edit:
I didn't realize ISO_WEEK was not available in SQL Server 2005. Since it's based on the Thursday of the week, the problem now shifts to finding the Thursday from the given day:
DECLARE #Date date = '2012-01-08'
DECLARE #Thursday date = DATEADD(DAY, 3-(DATEPART(WEEKDAY, #Date) + ##DATEFIRST - 2) % 7, #Date)
SELECT (DATEPART(DAYOFYEAR,#Thursday) - 1) / 7 +1

SQL Server date calculations in stored procedures

I wanted to ask 3 questions about below code (please excuse the long code listing, I am including these lines in the hopes that it provides enough context).
Note that the code here depends on the date when it is executed. For this reason my questions refer to a hypothetical situation with two different execution dates:
March 1st 2014
January 1st 2014
My questions are on whether my understanding on some parts of this is correct, i.e:
A. that the SELECT DATEADD expression (on line 1) would:
On March 1st 2014 create the datetime 2014-02-31 23:59:59
B. that the code on lines 6-9 would:
On March 1st 2014 create the datetime 2014-02-01 00:00:00
On January 1st 2014 create the datetime 2013-02-01 00:00:00
and
C. that the code on lines 11-14 would:
On March 1st 2014 create the datetime 2015-01-30 00:00:00
On January 1st 2014 create the datetime 2014-01-30 00:00:00
Is this understanding correct?
1. SET #ldpmth = (SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) )
2. SET #yr = (SELECT YEAR(#ldpmth))
3. SET #mth = 0
4. SET #dy = 0
5.
6. SET #fysdate = (SELECT CASE WHEN MONTH(#ldpmth) >= 2 THEN
7. DATEADD(MM, 1,CAST(CAST(#yr+#mth+#dy AS NVARCHAR(50)) AS DATETIME))
8. ELSE DATEADD(MM, 1, CAST(CAST((#yr-1)+#mth+#dy AS NVARCHAR(50))
9. AS DATETIME)) END )
10.
11. SET #fyedate = (SELECT CASE WHEN MONTH(#ldpmth) >= 2 THEN
12. DATEADD(YY, 1, CAST(CAST(#yr+#mth+#dy AS NVARCHAR(50)) AS DATETIME)) + 30
13. ELSE DATEADD(YY, 1, CAST(CAST((#yr-1)+#mth+#dy AS NVARCHAR(50))
14. AS DATETIME)) + 30 END )
(Thank you for all who answered so far. This is actually code that was developed (but not documented) at my place of employment some years ago and I have been tasked with converting it to a form that works client-side with Crystal Reports.)
On March 1st 2014 create the datetime 2014-02-31 23:59:59
No. AFAIK, there isn't any dbms that's so dumb it thinks Feb 31 is an actual date. The SQL statement on line 1 will return the value 'Feb 28 2014 23:59:59'.
You can test all your statements by substituting actual dates for GETDATE() and guesswork. In the first query, for example, use
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,'2014-03-01'),0));
^^^^^^^^^^
You can probably run a version of SQL Server locally. SQL Server 2008 even installs on Windows XP. If you can't bear that, though, there's always sqlfiddle.com.
This could be easily tested in SQL Server Management Studio (SSMS). I'll answer the first, and you can test the next two yourself.
Question:
A. that the DATEADD (on line 1) would on March 1st 2014 create the datetime 2014-02-31 23:59:59
Answer: No, because February can't possibly have 31 days, so it can't return '2014-02-31`
Proof:
select DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,'2014-03-01'),0))
Results
(No column name)
2014-02-28 23:59:59.000
For (B) and (C), if you'd stated your question, instead, as "My financial years run from 1st February until 30th(sic) January - how do I get the start and end dates for the current financial year, I'd have offered:
SET #fysdate = DATEADD(year,DATEDIFF(month,'19000201',GETDATE())/12,'19000201')
and:
SET #fyedate = DATEADD(year,DATEDIFF(month,'19000201',GETDATE())/12,'19010131')
(Note that this second finds the 31st Jan, not the 30th. I assume that was carelessness in your original question).
But, as to (A), as I indicated, I thought your question is again poorly phrased - if you're trying to find the end point of a period and that period is defined on datetimes (as opposed to just dates), it's far easier to construct an exclusive upper bound:
SET #ldpmth = DATEADD(month, DATEDIFF(month,0,GETDATE()),0)
This bound (to be used with a < comparison rather than <= or BETWEEN) doesn't artificially exclude any values with a time such as 23:59:59.527. Note also, that if the financial year end date calculation is going to be used against datetime values which include times, I'd again counsel computing an exclusive upper bound, and substitute 19010201 instead of 19010131.
So, in total, I don't think I've actually answered your questions as posed, but I think I've provided the answers you should have been seeking.

Getting week number off a date in MS SQL Server 2005?

Is it possible to create an sql statement that selects the week number (NOT the day of week - or the day number in a week). I'm creating a view to select this extra information along with a couple of other fields and thus can not use a stored procedure. I'm aware that it's possible to create a UDF to do the trick, but if at all possible i'd rather only have to add a view to this database, than both a view and a function.
Any ideas? Also where i come from, the week starts monday and week 1 is the first week of the year with atleast 4 days.
Related:
How do I calculate the week number given a date?
Be aware that there are differences in what is regarded the correct week number, depending on the culture. Week numbers depend on a couple of assumptions that differ from country to country, see Wikipedia article on the matter. There is an ISO standard (ISO 8601) that applies to week numbers.
The SQL server integrated DATEPART() function does not necessarily do The Right Thing. SQL Server assumes day 1 of week 1 would be January 1, for many applications that's wrong.
Calculating week numbers correctly is non-trivial, and different implementations can be found on the web. For example, there's an UDF that calculates the ISO week numbers from 1930-2030, being one among many others. You'll have to check what works for you.
This one is from Books Online (though you probably want to use the one from Jonas Lincoln's answer, the BOL version seems to be incorrect):
CREATE FUNCTION ISOweek (#DATE DATETIME)
RETURNS INT
AS
BEGIN
DECLARE #ISOweek INT
SET #ISOweek = DATEPART(wk,#DATE)
+1
-DATEPART(wk,CAST(DATEPART(yy,#DATE) AS CHAR(4))+'0104')
-- Special cases: Jan 1-3 may belong to the previous year
IF (#ISOweek=0)
SET #ISOweek = dbo.ISOweek(CAST(DATEPART(yy,#DATE) - 1
AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,#DATE) AS CHAR(2)))+1
-- Special case: Dec 29-31 may belong to the next year
IF ((DATEPART(mm,#DATE)=12) AND
((DATEPART(dd,#DATE)-DATEPART(dw,#DATE))>= 28))
SET #ISOweek=1
RETURN(#ISOweek)
END
GO
You need the ISO week. From http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=60510, here's an implementation:
drop function dbo.F_ISO_WEEK_OF_YEAR
go
create function dbo.F_ISO_WEEK_OF_YEAR
(
#Date datetime
)
returns int
as
/*
Function F_ISO_WEEK_OF_YEAR returns the
ISO 8601 week of the year for the date passed.
*/
begin
declare #WeekOfYear int
select
-- Compute week of year as (days since start of year/7)+1
-- Division by 7 gives whole weeks since start of year.
-- Adding 1 starts week number at 1, instead of zero.
#WeekOfYear =
(datediff(dd,
-- Case finds start of year
case
when NextYrStart <= #date
then NextYrStart
when CurrYrStart <= #date
then CurrYrStart
else PriorYrStart
end,#date)/7)+1
from
(
select
-- First day of first week of prior year
PriorYrStart =
dateadd(dd,(datediff(dd,-53690,dateadd(yy,-1,aa.Jan4))/7)*7,-53690),
-- First day of first week of current year
CurrYrStart =
dateadd(dd,(datediff(dd,-53690,aa.Jan4)/7)*7,-53690),
-- First day of first week of next year
NextYrStart =
dateadd(dd,(datediff(dd,-53690,dateadd(yy,1,aa.Jan4))/7)*7,-53690)
from
(
select
--Find Jan 4 for the year of the input date
Jan4 =
dateadd(dd,3,dateadd(yy,datediff(yy,0,#date),0))
) aa
) a
return #WeekOfYear
end
go
Looks like the DATEPART mssql function should help you out with ...
DATEPART(wk, ‘Jan 1, xxxx’) = 1
Well I'll be.. turns out there is a way to set the first day of the week, DATEFIRST
SET DATEFIRST 1 -- for monday
Update: Now I understand better, what the OP wants.. which is custom-logic for this. I don't think MSSQL would have functions with such rich level of customization. But I may be wrong... I think you'll have to roll your own UDF here...sorry
FORGET THE OTHER ANSWERS
The question specifies "the week starts monday and week 1 is the first week of the year with atleast 4 days." This is ISO 8601 standard and what this answer provides. This function is used in production on our site.
This is all you need:
CREATE FUNCTION ISOweek (#DATE DATETIME)
RETURNS INT
AS
BEGIN
RETURN (datepart(DY, datediff(d, 0, #DATE) / 7 * 7 + 3)+6) / 7
END
GO
This will return you the week number of date entered in quotes
SELECT DATEPART( wk, 'enter the date over here' )
Looks like datepart will get you part of the way there, but you'll have to adjust to get your correct week number, based on the day of week of Jan 1 of the given year. I'm not familiar enough with T-SQL to do that, but it should be possible. Pity there isn't a mode argument as in MySQL
have you considered using the WEEK function?
This will get you the week of the year for the specified date that you pass in.
SELECT { fn WEEK(GETDATE()) } AS WeekNumber, { fn WEEK(CONVERT(DATETIME, '2008-01-01 00:00:00', 102)) } AS FirstWeekOfYear, { fn WEEK(CONVERT(DATETIME, '2008-12-31 00:00:00', 102)) } AS LastWeekOfYear
This outputs the following SQL2000 and SQL2005:
WeekNumber: 50
FirstWeekOfYear: 1
LastWeekOfYear: 53
I Hope this helps :)
Why yet again, people make mountains out of mole-hills, it astounds me?
So simple...
select DATEPART(wk, GETDATE())

Resources