You are here: Re: Loop / Cursor help « MsSQL Server « IT news, forums, messages
Re: Loop / Cursor help

Posted by David Portas on 09/26/21 11:40

woodfoot wrote:
> Is there a way to do this without the use of a calendar table?
> thx

You could create the calendar in a table variable. It seems a bit
pointless to do that each month though. Calendar tables are useful for
all sorts of queries and reports. It's probably worth keeping one in
your database whether you use it for this or not.

DECLARE @t TABLE (cal_date DATETIME PRIMARY KEY);
DECLARE @month DATETIME;

SET @month = '20060201';

INSERT INTO @t VALUES (@month);

WHILE (SELECT MAX(cal_date) FROM @t)<DATEADD(MONTH,1,@month)
INSERT INTO @t (cal_date)
SELECT DATEADD(DAY,
DATEDIFF(DAY,@month,cal_date)+1,
(SELECT MAX(cal_date) FROM @t))
FROM @t;

INSERT INTO vehicle_useage (use_date, vin, miles)
SELECT C.cal_date, V.vin, 0
FROM vehicles AS V
JOIN @t AS C
ON C.cal_date >= @month
AND C.cal_date < DATEADD(MONTH,1,@month);

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация