September 4, 2009 at 12:22 pm
How would I insert the dates of the current month 2009-09-01, 2009-09-02, etc, etc, into a sql table using only sql?
September 4, 2009 at 12:32 pm
If you have a Numbers table (Tally table, Sequence table), it's easy:
select dateadd(day, number-1, '9/1/2009')
from dbo.Numbers
where number <= datediff(day, '9/1/2009', dateadd(month, 1, '9/1/2009'));
If you don't have a Numbers table, and don't want to create one (they're tremendously useful for a lot of things), you can use a CTE to generate one, like this:
;with Numbers (Number) as
(select row_number() over (order by object_id)
from sys.all_objects)
select dateadd(day, number-1, '9/1/2009')
from Numbers
where number <= datediff(day, '9/1/2009', dateadd(month, 1, '9/1/2009'));
You can, of course, use variables for the month you want, or columns, or any datetime calculation.
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
September 5, 2009 at 12:45 am
If you want to know how a Tally table (or CTE that works like one) replaces a Cursor or While Loop in many cases, please see the following article...
http://www.sqlservercentral.com/articles/T-SQL/62867/
--Jeff Moden
Change is inevitable... Change for the better is not.
September 5, 2009 at 2:14 pm
Just to keep this clear for the newcomers. A "numbers" table and a "tally" table are the same thing.
But "Tally Table" is much more alliterative and fun. 😉
__________________________________________________
Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills
September 7, 2009 at 2:32 pm
Is a numbers//tally//sequence table the same as a PIVOT table?
Thank you for the responses.
September 7, 2009 at 3:04 pm
Nope, it's just a table containing sequential numbers (1, 2, 3, 4, 5, ...) but there are many solutions which can be done with. You should read the article posted by Jeff. You can also find a link in my signature.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply