SQL SERVER – Script/Function to Find Last Day of Month

Following query will find the last day of the month. Query also take care of Leap Year. Script: DECLARE @date DATETIME SET @date='2008-02-03' SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date)) AS LastDayOfMonth GO DECLARE @date DATETIME SET @date='2007-02-03' SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date)) AS LastDayOfMonth GO ResultSet: LastDayOfMonth ----------------------- 2008-02-29 00:00:00.000 (1 row(s) affected)…
Read More

SQL SERVER – UDF – User Defined Function to Find Weekdays Between Two Dates

Following user defined function returns number of weekdays between two dates specified. This function excludes the dates which are passed as input params. It excludes Saturday and Sunday as they are weekends. I always had this function with for reference but after some research I found original source website of…
Read More

SQL SERVER – SQL Commandments – Suggestions, Tips, Tricks

Few days ago, while searching for something on web site, I came across a very good article of 25 SQL Commandments. I really enjoyed reading it. It was for Oracle, I re-wrote it for SQL Server. First 18 points are taken from original article and last 2 I added to…
Read More

SQL SERVER – Simple Cursor to Select Tables in Database with Static Prefix and Date Created

Following cursor query runs through the database and find all the table with certain prefixed (‘b_’,’delete_’). It also checks if the Table is more than certain days old or created before certain days, it will delete it. We can have any other operation on that table like to delete, print or index.

Read More