SQL to get all Month End and Begin Dates

Many web sites and blogs will tell you how to find the last day, first day of a month or year

But what if you need the month end and begin dates for a specific time period?  Well, here is the code for that:

–script to get month begining & end dates for a time period
–declare all variables
DECLARE @StartDate datetime
DECLARE @EndDate datetime
DECLARE @MonthEndDate datetime
DECLARE @MonthBeginDate datetime

DECLARE @MonthlyDates Table
(    MonthID INT NOT NULL IDENTITY(1,1),
MonthBeginDate SMALLDATETIME NOT NULL,
MonthEndDate SMALLDATETIME NOT NULL
)

–set the time period here
SET @StartDate = ’3/1/2009′
SET @EndDate = ’5/31/2012′

–Get the first month’s begin and end dates
SELECT @MonthBeginDate = DATEADD(dd,-(DAY(@StartDate)-1),@StartDate)
SELECT @MonthEndDate = DATEADD(mm,1,@StartDate) – DAY(DATEADD(mm,1,@StartDate))

–do the first insert into the holding table
INSERT INTO @MonthlyDates
(MonthBeginDate, MonthEndDate)
VALUES
(@MonthBeginDate, @MonthEndDate)

–use while loop to move through each month
WHILE @MonthEndDate < @EndDate
BEGIN

SELECT @MonthBeginDate = DATEADD(mm, 1, @MonthBeginDate)
SELECT @MonthEndDate = DATEADD(dd, -1, DATEADD(mm, 1, @MonthBeginDate))

INSERT INTO @MonthlyDates
(MonthBeginDate, MonthEndDate)
VALUES
(@MonthBeginDate, @MonthEndDate)

END
SELECT
MonthBeginDate,
MonthEndDate
FROM @MonthlyDates

So this code will give you all the months begin & end dates, in order.  Now in this code I’m not looking at when the @StartDate or @EndDate falls in the month.  For example, if I pass into the code a start date of March 10, 2009 it will return, as the first row, the begin and end dates for the month of March.  If you wanted to only return dates for whole months that your range covers (in the above example that would be a start month of April), you would need to alter the code.

Oh, and it is good for leap years too!

Good reference links for the TOP Keyword

This past week I needed to use the TOP keyword for some code and came across some excellent resources:

First, the quick basics of top:

Dynamically controlling the number of rows affected by a SQL Server query

Next, a good article on how to retrieve top and bottom rows together:

How to Retrieve TOP and BOTTOM Rows Together using T-SQL

And an excellent article on the TOP per group scenario:

Who’s On First? Solving the Top per Group Problem

And the book Inside Microsoft SQL Server 2008 T-SQL Querying there is a whole chapter mostly on TOP; Chapter 9 TOP and APPLY.

TOP isn’t something used everyday in SQL Server, but when you need it, you’ll be happy it’s part of TSQL.

No way to know it all…

The other day I was looking up some information about SQL Server Profiler and I came across this book “Mastering SQL Server Profiler” by Brad McGehee.  It is in PDF format, so I downloaded it and opened it up to take a look. 306 pages.  Oh my!  On just Profiler alone!  Then I grabbed another book, “SQL Server Execution Plans” by Grant Fritchey.  This one was 181 pages! And my Reporting Services book tops those two at 866 pages.

Ten years ago, when I started my first job in the database world, working with SQL Server 6.5, I could not have imagined the volume of information dedicated to SQL Server.  Back then, a whole book on the product was only 400-500 pages.  The product has grown so much that no one person could know it all.  Even the people considered the most knowledgeable about SQL Server typically specialize in just a part of it.  That’s probably why I have over 25 different SQL Server blogs in my RSS reader.  No one blog covers it all.

I have to remind myself to focus my self study efforts.  I have to partition out all the things I would like to know about SQL Server into two buckets:  stuff I need in my head and stuff I should just know to how to look up.   It’s less stressful that way.

Review of Microsoft SQL Server 2008 Reporting Services – Chapters 1 to 5

In December, just before Christmas, I picked up the book Microsoft SQL Server 2008 Reporting Services by Brian Larson.  Don’t ask me why I’m buying tech books just before the holidays…I didn’t have time to read it until after the new year….anyway I just finished the first 5 chapters of the book and here are my impressions.

Chapter 1 – All tech books seem to start with an overview and this one is no different.  I found the writing style easy to read and understand, unlike some other tech books I’ve read.  It is a good overview of Reporting Services, it start with the basics of the product and doesn’t assume the reader already knows about the product.  Since I have already worked with the previous two versions of Reporting Services, I skimmed over some portions of this chapter.

Chapter 2 – All about installing Reporting Services.  Since I had already installed the product before I read the chapter, this was mostly review too.  But, again, I found the writing style to be very easy to read.  Each step of the install process is documented and clearly explained.

Chapter 3 – The title of this chapter is Database Basics.  Which means if you have been working with SQL Server you don’t need to read this chapter, except for the few pages explaining the Galactic Delivery Services database, which the database is used throughout the book.  So I pretty much skipped this chapter.  Its target audience is readers new to databases and report writing.

Chapter 4 – This is where the actual work begins.  Or so I thought.  This chapter has you using the report wizard to write reports.  Frankly, I haven’t met anyone who actually creates reports this way.  I did go through the exercises anyway.  The book could do without this chapter, it doesn’t add any value to the book.

Chapter 5 – Oh yea! No more report wizard.  In this chapter you start with a blank report and build it up from the beginning.  I found the step by step directions to be very easy to follow.  Again, features of the product that would be used by a person new to databases and report writing are emphasized, such as the Graphical Query Designer (using that gave me flashbacks of Access 97).  But I did learn some new things such as the changes in BIDS (or VS 2008).

So, my first impression are this:  the book is very well written, but experienced folks will be skipping over pages to get to the real meat.

Report Manager Connection Issue in Reporting Services 2008

I’ve installed both RS 2000 & RS 2005 on various desktops and laptops in the past with no problems, so I figured getting RS 2008 up and running would be no big deal.  But I did run into a little problem along the way.

After the install, I tried to navigate to the Report Manager home page and I was greeted with a login box:

image

Hey I’m a local admin, I don’t need to log in. What gives!  So I scratched my head for a bit and then fired up Google.  But the information I found didn’t help me much. I tried several suggestions such as changing the account that RS Service runs in.  No luck with that.  Finally  I found a some help in one forum post (located at an MSND forum) that suggested changing the intranet security settings.  I wasn’t sure if it would work because I was on a different version of Windows (XP vs.. Vista), and they described a somewhat different set of problems, but I figured it was worth a try.  After some trial and error I put my URL in the allowed sites box, and it worked!

The link above gives the step by step for solving this, but here are some pictures showing what I did to fix the problem:

First go to Tools, Internet Options, Security Tab. Click on Local Intranet.

image

Then click on the “Sites” button to bring this screen up.

image

Click on the Advanced button and enter the URL in the “Add websites to this zone” box.  Click Add.

image

Click Close or Ok to back out of the boxes.  Refresh your screen and you are done!  Report Manager should appear now.

2010 – Oh my a New Year!

I have spent the last few weeks thinking about what the new year and the new decade will bring.  I am happy to leave 2009, which was a strange year, at least I felt strange about it.  Not much was accomplished in my civilian career because I spent much of the year deployed to Kosovo with the National Guard.  It was an interesting experience, but it put me behind in building new skills for my civilian career.  So….2010 is the year to jump start my career.  Fortunately, I do have a good job, one that will provide excellent experience for me in the coming year.

So other then doing my day to day work at my job, what I am going to do to jump start and beef up my SQL Server skill set? I will focus on the following 3 items:

  1. Increase my blogging.  My goal this year is to post at least once per week, 52 times this next year.  Writing about a subject is a good learning experience, at least for me.
  2. Take and pass the two exams for SQL Server 2008 development,  70-433 & 70-451.
  3. Attend at least 4 in-person events relating to SQL Server.  This could be a code camp, PASS, local user group, or some classroom training.  It just has to be in person and related to SQL Server in some way.

So, here’s to a great new year!

Back to Work!

Now that I am back home from my deployment to Kosovo, I’ve gone back to work.  My first day back was Monday, December 7th.  It was nice to come back, but I was a little nervous that first day thinking about what changed while I was gone.  Now that I’ve been back for 4 days now, I feel a bit silly that I was nervous last Monday…there are many good changes.  Most of our servers are now running SQL Server 2005 and we have a major upgrade project that is being developed on SQL Server 2008.  It’s nice to be moving off SQL 2000.

It feels good to be back.  2010 will be a great year!

The New Date & Time Datatypes are great, but…

The first time I read about the new Date and Time datatypes I though “Well, that’s nice”.  But the more I think about it the happier I am.  No more stripping off the time values to do a date only comparison.  Thank goodness.   Some other pluses;  possible use of indexes, safe to use BETWEEN for date ranges, easier reading of code without all of those CONVERT functions. 

But don’t be so eager to leave out the time part.  You need to be absolutely sure that you don’t need the time piece.  If your not sure, keep the time part in a column separate from the date.

There is some good sample data for these datatypes in the AdventureWorks2008 database.  Take a look at the Human Resources.Employee table, Birthdates & Hire Date columns.  And also look at Human Resources.Shift table, Start Time & End Time columns.

Linker Servers and Server Aliases

Just the other day I received a call from a developer with a database problem. He was receiving timeouts when he called a particular stored procedure from his application. So I took a look at the proc, reviewed the code, and tried to run it. It just ran and ran and ran, no error messages, nothing. Then I tried to recompile the proc, same thing, just hung. So I stopped it, looked at the amount of data it needed to run, not much data involved, so I cut the proc into pieces and ran it a chuck at a time. Finally, I got to the problem part of the code, the part that just hung. In reading the code, I noticed that it was referencing a linked server, hmmm, where does this point to? So, I go into the Client Network Utility and here we are, an old server that no longer exists! Change the server name and port number and yes! The proc complies and runs! Weird, wonder why it just didn’t just return an error message. Oh well, all in a day’s fun!

Table Aliases are Wonderful. Use them on all columns!

Notice the lack of table aliases for the select list:

Select  FirstName,
            LastName,
            c.ID,
            Address1,
            Address2,
            State,
            Zip,
            Phone1,
            Phone2,
            Email,
            RegionName,
            EmployeeName
FROM Customers c
JOIN Location l
          ON c.ID = o.ID
JOIN Contact c
          ONc.ID = o.id
WHERE c.ID = @ID

Don’t do this!

If this was a database you just inherited from the last guy (or gal), it might not be obvious which column goes to which table.  So you have to take the time to figure that out before you can make the necessary changes.  And that is just wasted time. 

If you are writing a multi-table query, please use table aliases on every column in the select.  The next person to work on the code will thank you.