Execute T-SQL Code Only on Certain Days

I always clean up my databases manually on Sundays. But at times, if need be, I clean it up on other days as well. However I never do it on Saturdays, since the traffic is usually the most on that day.

So here’s a simple tip using IF-ELSE to prevent my T-SQL code from running on Saturday’s, even if I run the code manually

IF DATEPART(dw,GETDATE())<> 7  -- 7 is Saturday, 1 is Sunday
-- YOUR T-SQL Code Comes Here
'*** Sorry This Code will Not Execute on Saturdays'



You may also want to read Make a T-SQL Query Sleep for a certain amount of time

About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook


Dattatrey Sindol said...

Hi There,

DATEPART() function does not return the same value in all the situations since it depends on the settings of SET DATEFIRST option. Instead use DATENAME() function.

Refer to the following links for more details:

1. http://dattatreysindol.blogspot.com/2010/08/query-to-get-week-start-date-month.html
2. http://msdn.microsoft.com/en-us/library/ms174420.aspx

Dattatrey Sindol (Datta)

Anonymous said...

Thank you for this helpful piece of code. As written upper, the day marked as first depends on the SET DATEFIRST option.