A calendar table is useful in a variety of situations that involve date calculations. (Pffft! As if you didn’t know that!!) If you have a Numbers table in your database, generating a calendar from that is very easy. But, if you don’t have one, (then shame on you! You should create one) here is a quick way to generate a calendar table.
By the way, for once, I am blogging this here not for your entertainment, but for my own purpose. I find that I need to create calendar tables very often, I know how to do it, it takes just 3 minutes, but I am tired of typing it every time. So I came up with the brilliant idea of putting it here, so I can copy and use it any time I want. (That does not mean you should. Go ahead and type it every time. You will learn a lot by doing that! Really!!).
So with further ado (or is it “without further ado”?) here is my brilliant creation:
CREATE TABLE #Calendar(Dt DATE NOT NULL PRIMARY KEY CLUSTERED);
DECLARE @startDate DATE = '20130701';
DECLARE @endDate DATE = '20130731';
;WITH cte AS
SELECT CAST(@startDate AS DATE) AS Dt
SELECT DATEADD(dd, 1,Dt) FROM Cte
WHERE Dt < @endDate
INSERT INTO #Calendar SELECT Dt FROM cte OPTION (MAXRECURSION 0);
If you don’t have permissions to create tables (of any variety – temporary or permanent), you can use a table variable instead of a temp table. Or, you can just embed that CTE into your query and bypass having to create even table variables.
Speaking of temp tables, user tables, table variables etc., do you know what the difference (or differences) between a temp table and a table variable is (are)? There was this awesome response that I saw someone post somewhere enumerating the differences – it was quite comprehensive and thoroughly entertaining. I can’t find it now, but when I do, I promise I will steal from it and post another blog here pretending as though it is all my invention.