I'm using SS 2005 if that
I've seen sample code like
DECLARE #restore = SELECT ##DATEFIRST
SET DATEFIRST 1
SELECT datepart(dw,ADateTimeColumn) as MondayBasedDate,.... FROM famousShipwrecks --
SET DATEFIRST #restore
Suppose while the query is running another query sets DATEFIRST?
If another query relies on datefirst being 7 (for example) and doesn't set it, and runs while my query is running, that's his problem for not setting it? or is there a better way to write queries that depend on a given day being day number 1.
##DATEFIRST is local to your session. You can verify it by opening to tabs in Sql Server Management Studio (SSMS). Execute this code in the first tab:
SET DATEFIRST 5
And verify that it doesn't affect the other tab with:
select ##datefirst
See this MSDN article.
Just an additional point, if you want to avoid setting DATEFIRST you can just incorporate the value of DATEFIRST in your query to find your required day as :
SELECT (datepart(dw,ADateTimeColumn) + ##DATEFIRST) % 7) as 'MondayBasedDate'
, ...
FROM famousShipwrecks --
Then you dont need to worry about restoring it at all!
To setup a parameterized first day of the week, the following should work
DECLARE #FirstDayOfWeek INT = 1;
DECLARE #DateTime DATETIME = '2015-07-14 8:00:00';
SELECT (DATEPART(weekday, #DateTime) + ##DateFirst - #FirstDayOfWeek - 1) % 7 + 1;
You can forget about DATEPART(weekday, DateColumn) and ##DATEFIRST and instead calculate the day of the week yourself.
For Monday based weeks (Europe) simplest is:
SELECT DATEDIFF(day, '17530101', DateColumn) % 7 + 1 AS MondayBasedDay
For Sunday based weeks (America) use:
SELECT DATEDIFF(day, '17530107', DateColumn) % 7 + 1 AS SundayBasedDay
This works fine ever since January 1st respectively 7th, 1753.
Related
Something like this (which is not working)
CREATE FUNCTION dbo.udf_DayOfWeek
(#b_date DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE #weekday VARCHAR(10)
IF (SELECT DATENAME(dw, #b_date)
RETURN (#weekday)
END;
GO
after using this
SELECT dbo.udf_DayOfWeek ('May 22, 2016');
GO
to return value of 1-7(number of a day in week)
I am using SQL Server 2014
You are going to want to use DATEPART() versus DATENAME() to get the numeric value, but this can be done inline and really doesn't need it's own function.
SELECT DATEPART(weekday,'May 22, 2016')
And to fix your function syntax...
CREATE FUNCTION dbo.udf_DayOfWeek (#b_date DATETIME)
RETURNS INT
AS
BEGIN
DECLARE #weekday INT
SELECT #weekday = DATEPART(WEEKDAY, #b_date)
RETURN (#weekday)
END
GO
DatePart for weekday uses the DateFirst setting, making it difficult to use consistently. The problem is, some places in the world consider Sunday to be the first day of the week, and other places consider Monday to be the first day of the week. Because of this ambiguity, SQL Server will use the datefirst setting of the login currently connected to the database. To see a list of datefirst settings, run this:
Select * From sys.syslanguages
You can manually set the DateFirst value that persists for the duration of the connection like this:
Set DateFirst 1
SELECT DATEPART(weekday,'May 22, 2016')
Set DateFirst 7
SELECT DATEPART(weekday,'May 22, 2016')
Note that the output of the previous code changes depending on the DateFirst setting.
If you want 1 to always represent Sunday, regardless of the user's language setting, you can use this:
Select DateDiff(Day, 6,#DateVariable) % 7 + 1
Using this information, you can create your user defined function like this:
CREATE FUNCTION dbo.udf_DayOfWeek
(#b_date DATETIME)
RETURNS int
AS
BEGIN
return (
Select DateDiff(Day, 6,#b_date) % 7 + 1
)
END;
I have a Query where I get the WeekDay of a date but by default:
Sunday = 1
Moday = 2
etc.
The function is:
DATEPART(dw,ads.date) as weekday
I need the result so:
Sunday = 7
Monday = 1
etc.
Is there any shortcut to do this? Or I will have to do a CASE statement?
This will do it.
SET DATEFIRST 1;
-- YOUR QUERY
Examples
-- Sunday is first day of week
set datefirst 7;
select DATEPART(dw,getdate()) as weekday
-- Monday is first day of week
set datefirst 1;
select DATEPART(dw,getdate()) as weekday
You can use a formula like:
(weekday + 5) % 7 + 1
If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.
addition:
for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :
(weekday + ##DATEFIRST + 5) % 7 + 1
You can tell SQL Server to use Monday as the start of the week using DATEFIRST like this:
SET DATEFIRST 1
I would suggest that you just write the case statement yourself using datename():
select (case datename(dw, aws.date)
when 'Monday' then 1
when 'Tuesday' then 2
when 'Wednesday' then 3
when 'Thursday' then 4
when 'Friday' then 5
when 'Saturday' then 6
when 'Sunday' then 7
end)
At least, this won't change if someone changes the parameter on the day of the week when weeks begin. On the other hand, it is susceptible to the language chosen for SQL Server.
You can use this formula regardless of DATEFIRST setting :
((DatePart(WEEKDAY, getdate()) + ##DATEFIRST + 6 - [first day that you need] ) % 7) + 1;
for monday = 1
((DatePart(WEEKDAY, getdate()) + ##DATEFIRST + 6 - 1 ) % 7) + 1;
and for sunday = 1
((DatePart(WEEKDAY, getdate()) + ##DATEFIRST + 6 - 7 ) % 7) + 1;
and for friday = 1
((DatePart(WEEKDAY, getdate()) + ##DATEFIRST + 6 - 5 ) % 7) + 1;
Another solution is the following:
ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)
This is caused by the account the SQL Server service is run under. For example;
If the SQL Server Service is run under DOMAIN\MyUserAccount then this will need to be a login and set with the relevant Language.
If this account isn't set then SQL Server will default to the sa account and the Language that runs under.
I found that our sa account was set to English which had Monday as DW = 2. The DOMAIN\MyUserAccount Account was setup and changed to British English and DW for Monday was being returned as 1.
Hope this helps
Simply subtract one day from your ads.date field and use in DATEPART function:
DATEPART(dw,DATEADD(day,-1,ads.date)) as weekday
I think this could work:
select
case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
Try this:
CREATE FUNCTION dbo.FnDAYSADDNOWK(
#addDate AS DATE,
#numDays AS INT
) RETURNS DATETIME AS
BEGIN
WHILE #numDays > 0 BEGIN
SET #addDate = DATEADD(day, 1, #addDate)
IF DATENAME(DW, #addDate) <> 'sunday' BEGIN
SET #numDays = #numDays - 1
END
END
RETURN CAST(#addDate AS DATETIME)
END
Looks like the DATEFIRST settings is the only way, but it's not possible to make a SET statement in a scalar/table valued function. Therefore, it becomes very error-prone to the colleagues following your code. (become a trap to the others)
In fact, SQL server datepart function should be improved to accept this as parameter instead.
At the meantime, it looks like using the English Name of the week is the safest choice.
-- Monday is first day of week set datefirst 1; select DATEPART(dw,getdate()) as weekday
SQLChao answer still works prefectly well
You would need to set DATEFIRST. Take a look at this article. I believe this should help.
https://learn.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql
I think
DATEPART(dw,ads.date - 1) as weekday
would work.
I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
WHERE CloseTime >= DATEADD(Month, DATEDIFF(Month, 0, DATEADD(m, - 6, CURRENT_TIMESTAMP)), 0)
This gets me data for the month I am starting this script + 6 last months. So e.g. if I run this script today, Ill get the data for this month + all previous months till April (04).
Now I need to modify the condition so if I run the script today, the data will be obtained only for months 03-09 only, exluding days in this month (10).
Any advice, please?
If you want to have the previous 6 months regardless of whether today is the 1st, 3rd, 9th, 29th, whatever, then just subtract 7 months. Here is one way to do that: get the first of the month into a variable, then use an open-ended range in the query.
DECLARE #ThisMonth DATETIME;
SET #ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
SELECT...
WHERE CloseTime >= DATEADD(MONTH, -7, #ThisMonth)
AND CloseTime < #ThisMonth;
You could also use 0 in place of '19000101' but I prefer an explicit date than implicit shorthand (it was a very tough habit to break).
If you really don't like variables, then you can make the query a lot more complex by repeating the expression to calculate the first of this month (and in the start of the range, subtract 7 from the number of months):
SELECT...
WHERE CloseTime >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CloseTime < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
Yuck. Variables make this much tidier.
When creating queries you do not want to use a function on the search column since it will result in a full table scan.
The solution works and should pick up any index on CloseTime.
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
CloseTime between
DATEADD(d, -1, '03-01-2013') and DATEADD(d, +1, '09-20-2013')
If the table is small and a full table scan is not a issue, a simple solution is to use the MONTH function.
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
MONTH(CloseTime) IN (3,4,5,6,7,8,9) and YEAR(CloseTime) = 2013
I looked at Aaron's article. Its a very good read.
I wondered if there was some new function that was not tested since that article.
If you are using 2012, why not use the format function? Logically, you want date variables with a 01 day. The query plan still gets a clustered index scan.
Let's see how this solution stacks up using Aaron's test database.
-- Use the sample
use [DateTesting]
go
-- Johns - log by 6 months
CREATE PROCEDURE dbo.Johns_LogBy6Months
#date SMALLDATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmp_date SMALLDATETIME = format(#date, 'yyyyMM01');
DECLARE #c INT;
SELECT #c = COUNT(*)
FROM dbo.SomeLogTable
WHERE DateColumn >= dateadd(m, -7, #cmp_date)
AND DateColumn < #cmp_date
END
GO
-- Aarons - log by 6 months
CREATE PROCEDURE dbo.Aarons_LogBy6Months
#date SMALLDATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE #c INT;
DECLARE #cmp_date SMALLDATETIME = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #date), '19000101');
SELECT #c = COUNT(*)
FROM dbo.SomeLogTable
WHERE
DateColumn >= dateadd(m, -7, #cmp_date)
AND DateColumn < #cmp_date
END
GO
Lets make 1000 calls to the functions.
-- Sample calls x 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
EXEC dbo.Johns_LogCountByDay #date = '20091005';
GO 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
EXEC dbo.Aarons_LogBy6Months #date = '20091005';
GO 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
Here are the executions times.
2013-10-10 11:58:49.547
Beginning execution loop
Batch execution completed 1000 times.
2013-10-10 11:58:52.837
Beginning execution loop
Batch execution completed 1000 times.
2013-10-10 11:58:55.883
In summary a call to the new format() function and a implicit cast to a small date time takes a little more time than a dateadd() and datediff() with two string (date) literals.
The format() solution seems more intuitive or self documenting to me. The time difference was 3.3 versus 3.0 sec.
I have to give the speed test a win to Aaron's solution. Stick with in-equality comparisons of date variables. They are faster.
In short, I will have to fix my bad habits.
I had a similar request. I needed last six months and next six months of appointments. But just like you I needed the full months. So a simple getdate +- 180 wouldn't do.
I took a more simple approach. I get the year and month and turn it into a number like 201912. Then do a between clause. Its dynamic and I get full months.
I'm sure there's more sophisticated approaches, but this is what I came up with.
WHERE Year([ApptDate])*100 + Month([ApptDate]) between Year(getdate()-180)*100 + Month(getdate()-180) and Year(getdate()+180)*100 + Month(getdate()+180)
SELECT Date_Received, DateAdd(Year, DateDiff(year, Cast('3/01/2010 12:00:00AM' as DateTime) ,
GetDate())-1, Cast('3/01/2010 12:00:00AM' as DateTime)) as minimum_date
FROM [Volunteers].[dbo].[Applications]
WHERE Date_received >= DateAdd(Year, DateDiff(year, Cast('3/01/2010 12:00:00AM' as DateTime),
GetDate())-1, Cast('3/01/2010 12:00:00AM' as DateTime))
In several subqueries where I need to check that a date is within an acceptable range. I need to avoid using a simple constant as I really don't want to update it or a config file each new school year.
My current solution is to enter the date into the query and use some complicated DATEADD tricks to get the current year(or previous year) into the date I am using in the comparison. The exact code is above. Is there a cleaner way for me to do this?
Thanks
Edit
The business requirement is to find applications submitted between 3/01 and 7/31.
We are running background checks and it costs us money for each check we do. Identifying applications submitted during this time period helps us determine if we should do a full, partial or no background check. I will also need to check if dates concerning the previous year.
We will be doing this every year and we need to know if they were in the current year. Maintaining the queries each year to update the dates is not something I want to do.
So I am looking for a good technique to keep the year parts of the dates relevant without having to update the query or a config file.
Old TSQL trick: cast the date to a string in a format that starts with the four-digit year, using substring to take the first four characters of that, cast it back to a date.
Actually, the reason that it's an old TSQL trick is that, if I recall correctly, there wasn't a year() function back then. Given that there's one now, using year( getdate() ) , as others' have answered, is probably the better answer.
SELECT YEAR(GETDATE())
will give you the current year.
If you need to query by month and year a lot, you should also consider making those properties into persisted, computed fields:
ALTER TABLE dbo.Applications
ADD DateReceivedMonth AS MONTH(Date_Received) PERSISTED
ALTER TABLE dbo.Applications
ADD DateReceivedYear AS YEAR(Date_Received) PERSISTED
SQL Server will now extract the MONTH and YEAR part of your Date_Received and place them into two new columns. Those are persisted, e.g. stored along side with your table data. SQL Server will make sure to keep them up to date automatically, e.g. if you change Date_Received, those two new columns will be recomputed (but not on every SELECT).
Now, your queries might be a lot easier:
SELECT (list of fields)
FROM dbo.Applications
WHERE DateReceivedYear = 2010 AND DateReceivedMonth BETWEEN 3 AND 7
Since these are persisted fields, you can even put an index on them to speed up queries against them!
Is there any reason you cannot simply use the Year function?
Select Date_Received
, Year(GetDate())
- Year('3/01/2010 12:00:00AM') - 1
+ Year('3/01/2010 12:00:00AM')
From [Volunteers].[dbo].[Applications]
Where Date_received >= ( Year(GetDate())
- Year('3/01/2010 12:00:00AM') - 1
+ Year('3/01/2080 12:00:00AM') )
Another way would be to use a common-table expression
With Years As
(
Select Year(GetDate()) As CurrentYear
, Year('3/01/2010 12:00:00AM') As ParamYear
, Year('3/01/2080 12:00:00AM') As BoundaryYear
)
Select Date_Received
, CurrentYear - Years.ParamYear - 1 + Years.ParamYear
From [Volunteers].[dbo].[Applications]
Cross Join Years
Where Date_received >= ( Years.CurrentYear
- Years.ParamYear - 1 + Years.BoundaryYear )
TSQL Function returns four digit year dependent on year. This behaves much like the standard SQL YEAR functions [Thomas - nod] which 'CAN' be tweaked using sp_configure on the advanced options, however, the code below is provided as a framework for CUSTOM requirements and can be modified as required. e.g. return as int, use with standard DATETIME functions in SQL to achieve what is needed. e.g. When working with "dirty" data I had to migrate, I used it with the PATINDEX() function to strip non-numeric values etc.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andrew McLintock
-- Create date: 13 July 2016
-- Description: Return 4-digit YEAR
-- =============================================
/*
SELECT Staging.fn_4year('06')
SELECT Staging.fn_4year('56')
SELECT Staging.fn_4year('99')
SELECT Staging.fn_4year('1906')
SELECT Staging.fn_4year('2025')
*/
CREATE FUNCTION Staging.fn_4year
(
#year_in varchar (4)
)
RETURNS varchar(4)
AS
BEGIN
DECLARE #yeartmp int, #Retval varchar(4)
SET #yeartmp = CAST(REPLACE(#year_in,' ','') AS INT)
IF LEN(CAST(#yeartmp AS Varchar)) = 4
BEGIN
Return cast(#yeartmp as varchar(4))
END
IF LEN(#year_in) = 2
BEGIN
SET #Retval = CAST(iif(#yeartmp > 49, #yeartmp + 1900, #yeartmp + 2000) AS varchar(4))
END
RETURN #Retval
END
GO
Consider keeping a set of datetime variables help readability and maintainability. I'm not sure I've captured all your requirements, especially with reference to 'previous year'. If it's as simple as finding applications submitted between 3/01 and 7/31, then this should work. If you need to determine those that were submitted Aug 1 (last year) through Feb 28 (current year), this solution could be modified to suit.
DECLARE #Start smalldatetime, #End smalldatetime, #CurrYear char(4)
SELECT #CurrYear = YEAR(getdate())
SELECT #Start = CAST( 'mar 1 ' + #CurrYear as smalldatetime),
#End = CAST( 'jul 31 ' + #CurrYear as smalldatetime)
SELECT *
FROM Applications
WHERE Date_Received
BETWEEN #Start AND #End
I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])