Well, I'm going nuts.
It just struck me that the answer to my overall problem is to do some string manipulation and then DATEADD, but I still don't know why I getting what SQL is giving me.
To get the prior month, I use the following code;
SELECT ( SELECT RIGHT('00' + CAST( CASE CAST(RIGHT(MAX(Eff_Period), 2) AS int) - 1 WHEN 0 THEN 12 ELSE CAST(RIGHT(MAX(Eff_Period), 2) AS int) - 1 END AS varchar(2)), 2) )--, -- Month --CAST(CAST(LEFT(MAX(Eff_Period), 4) AS int) - 1 AS varchar(4)) -- Year FROM Current_Membership;
This correctly gives me the proper month number for the prior month, in this case, '06' since the current month is '07.'
But, for debugging, I wanted to test to make sure it would properly adjust for January - '01' - by replacing MAX(Eff_Period) with '201501.'
It did. Worked fine. Cool!
Then, to make really sure, I put in '201502.'
Whoa!!
Instead of the single record of '01,' it shot out 177,209 rows of all '02's!
I put back in the MAX(Eff_Period) instead of the date string constant and, worked fine. Swapped back in the date string - boom! - 177,209 rows again.
Like I said, I can use DATEADD - which, I should have thought of earlier, being familiar with it - but, still, what the hey is going on? Any ideas?
Alright. Now I'm really confused. I changed the date string to '201501' just to verify before posting this, and it spit out 177,209 rows of '01's! So, to keep from altering things and to maintain the edit history, I started up another query and C&P'd everything to it. Then, on the original, I backed up to an earlier version, one that worked. That listing is the same as above, but the commented out comma in line 9 and the commented CAST in the line after it - to get the year - were uncommented.
Now, it works with both '201501' and '201502.' But, if I replace the comments, basically removing the CAST with the year, it slams back with 177,209 rows!
My brain is starting to hurt from banging it on my desk in frustration - any thoughts on just what is going on?