Find last Friday in SQL Server 2008

Saturday, September 12, 2009 |


Microsoft SQL Server has very rich tools for date and time but just due to unawareness people find it difficult to make operation on datetime in SQL Server and used to go to front-end languages like .NET. I used to prefer SQL Server for performance issue. So far I have written quite a few articles on date time operation in SQL Server which is as follow.






If you will go through above given articles, you will come to know that datetime functions are really very handy and useful. Anyway, the main purposes to write this article to show you one another very small T-SQL for find out last Friday of the day.


SELECT DATEADD(day, (DATEDIFF (day, '19800104', CURRENT_TIMESTAMP) / 7) * 7, '19800104') as 'Last Friday'



It was really very easy. Right?

Actually the logic behind this small query is, there was a Friday on 4th Jan 1980 so I am getting difference between 4th Jan 1980 to current date, dividing it with 7 than multiplying with 7 and whatever number comes, I am adding it to the same date and I will get last Friday.


Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder ofhttp://www.SQLHub.com

0 comments: