April 28, 2008 at 10:09 pm
Hi
I've been trying to get a query to get all the days of the month passing in a month and year variable but just don't have a clue on how to do this.
I'm hoping a kind person from here can help me with this.
Thanks 🙂
April 29, 2008 at 1:13 am
It depends on how you want to access to this functionality.
the base code can be like
use AdventureWorks
go
DECLARE @pYear INT, @pMonth INT
DECLARE @pDateWork SMALLDATETIME, @pDateControl SMALLDATETIME
SET @pYear = 2008
SET @pMonth = 2
SET @pDateWork = CONVERT(SMALLDATETIME, CONVERT(VARCHAR,@pYear) + '-' +
CONVERT(VARCHAR,@pMonth) + '-1', 120)
SET @pDateControl = DATEADD(mm,1, @pDateWork)
WHILE @pDateWork < @pDateControl BEGIN
PRINT @pDateWork
SET @pDateWork = DATEADD(dd,1,@pDateWork)
END
You can access this by an userdefined Function or Stored Procedure
w. lengenfelder
April 29, 2008 at 2:24 am
For a single result set that you can join to...
--===== Declare your parameters
DECLARE @pYear INT, @pMonth INT
--===== Set the parameters (simulates a proc or udf parameters)
SELECT @pYear = 2008,
@pMonth = 2
SELECT t.N-1+DATEADD(mm,@pMonth-1,DATEADD(yy,@pYear-1900,0)) --Tally count-1 + 1st of desired month
FROM dbo.Tally t
WHERE t.N-1+DATEADD(mm,@pMonth-1,DATEADD(yy,@pYear-1900,0))
< DATEADD(mm,@pMonth,DATEADD(yy,@pYear-1900,0)) --First of next month
If you don't already have a Tally Table, now would be a good time. See the following for how to make one...
http://www.sqlservercentral.com/scripts/Advanced+SQL/62486/
--Jeff Moden
Change is inevitable... Change for the better is not.
April 29, 2008 at 9:51 pm
So... did that work for you or what?
--Jeff Moden
Change is inevitable... Change for the better is not.
May 8, 2008 at 3:49 pm
Jeff,
I have seen you use a tally table way too many times (this is not a bad thing ;)). When I saw the title to this post, even before seeing the thread, I thought "Hmmm, couldn't you use a tally table for this?" (I figured I would see you posting if someone hadn't mentioned it, would have been surprised if you didn't :ermm: )
Ian.
"If you are going through hell, keep going."
-- Winston Churchill
May 8, 2008 at 8:20 pm
Ian Crandell (5/8/2008)
Jeff,I have seen you use a tally table way too many times (this is not a bad thing ;)). When I saw the title to this post, even before seeing the thread, I thought "Hmmm, couldn't you use a tally table for this?" (I figured I would see you posting if someone hadn't mentioned it, would have been surprised if you didn't :ermm: )
Yeah... it had the word "Tally" written all over it. Couldn't resist it. 😀
Sure wish the OP would let me know if that did it for him.
--Jeff Moden
Change is inevitable... Change for the better is not.
May 9, 2008 at 1:57 am
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply