Solved

Inserting records; increment weekly

Posted on 2013-02-05
10
234 Views
Last Modified: 2013-02-05
Looking for a function in SQL (2008) where I can repeatedly enter a new row, incrementing two date fields (by 7 days each time)...

Insert into MyTable Values (Field1, Field2, StartDate, EndDate)

With start date beginning at 02/04/2013, end date beginning at 2/10/2013 and both continuing until year-end (or so)...
0
Comment
Question by:sirbounty
  • 4
  • 4
  • 2
10 Comments
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38855685
You may use a cursor(for the repetition) and DATEADD function for the increment of the dates

Giannis
0
 
LVL 67

Author Comment

by:sirbounty
ID: 38855703
cursor?
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38855776
Here is a sample code:

DECLARE @MyTable Table
(
	StartDate DATETIME,
	EndDate DATETIME
)

DECLARE @InitialStartDate DATETIME
DECLARE @InitialENDDate DATETIME

DECLARE @StopDate DATETIME

SET	@InitialStartDate = '20130402'
SET	@InitialENDDate = '20131002'
SET	@StopDate = '20131231'


DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

Insert into @MyTable Values (@InitialStartDate,@InitialENDDate)


DECLARE IncrementalInsert CURSOR FOR
SELECT	MAX(StartDate), MAX(EndDate)
FROM	@MyTable 

OPEN IncrementalInsert 
FETCH NEXT FROM 
IncrementalInsert 
INTO @StartDate, @EndDate

WHILE @StartDate<@StopDate
BEGIN 

	SET @StartDate = DATEADD(dd,7,@StartDate)
	SET @EndDate = DATEADD(dd,7,@EndDate)

	--INSERT INTO @MyTable Values ( @StartDate, @EndDate)
	SELECT * FROM @MyTable


	FETCH NEXT FROM IncrementalInsert INTO @StartDate, @EndDate
END 
 
CLOSE IncrementalInsert 
DEALLOCATE IncrementalInsert

Open in new window


Giannis
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38855798
In my scenario i create a table variable in order to store the dates. You don't need to do that as you already have the table, but my code is just a demonstration.

For simplicity i have only the date fields but you may have your other fields too.

Then i declare my starting dates and the date after which i need the loop to stop.

After that, i insert the first row and in the loop i insert the dates incremented by 7.

When my start date becomes greater than the 'StopDate' i quit the loop.

I hope it is clear what i am doing....

Giannis
0
 
LVL 67

Author Comment

by:sirbounty
ID: 38855908
Still going through it, but that helps some.
When I run it, it doesn't seem to be incrementing as is.

I get the date setup, and the loop, but I'm not sure about the table setup.
In your example, you declare a table with only start & end dates.  
Would I add the other columns in my table to that (and their data types)?
How would I reference that to my actual table name?

Does this section

SELECT      MAX(StartDate), MAX(EndDate)
FROM      @MyTable

Actually state to grab what's already in the rows?  I'm okay with that method, just trying to understand the code...

I'm having trouble with the while definition as well...
WHILE @StartDate<@StopDate
StartDate will always be < StopDate, won't it?
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38855962
The table variable is just to show you an example. You should actualy use your table.

The select max is to just get your starting dates if you actually have data in your table.

If you see every time you enter in the loop it increments the @StartDate so at some point it will be greater than the @StopDate.

Giannis
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 250 total points
ID: 38855992
A "tally" table works great for that.  It's much faster than looping, and much easier to change.


DECLARE @startDate datetime
DECLARE @last_date_to_generate datetime

SET @startDate = '20130204' --<<-- change as needed
SET @last_date_to_generate = '20131231' --<<-- change as needed

;WITH
cteDigits AS (
    SELECT 0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
    SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
),
cteTally AS (
    SELECT [10s].digit * 10 + [1s].digit AS num
    FROM cteDigits [1s] -- 0-9
    CROSS JOIN cteDigits [10s] -- 00-99 (100 total)
    --can add more if need more than 100 values    
)
INSERT INTO dbo.MyTable ( field1, field2, startDate, endDate )
SELECT 'field1', 'field2', DATEADD(DAY, num * 7, @startDate), DATEADD(DAY, num * 7 + 6, @startDate)
FROM cteTally
WHERE
    num BETWEEN 0 AND DATEDIFF(DAY, @startDate, @last_date_to_generate) / 7 - 1
ORDER BY
    3
0
 
LVL 67

Author Comment

by:sirbounty
ID: 38856022
That code gives me :Incorrect syntax near 'testdata'
on the line that reads:

INSERT INTO dbo.tblcollaboncall (NewID, startDate, endDate, 'testdata',1,0)
0
 
LVL 67

Author Closing Comment

by:sirbounty
ID: 38856666
Ah, took me a bit to figure it out, but that ended up being quick and simple once I got my head wrapped around it - thanx! :^)
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 38856982
Sweet!

If you need to read data from an existing table -- that is, take row(s) from an existing table and combine them with all the dates -- you can do this:


INSERT INTO dbo.MyTable ( field1, field2, startDate, endDate )
SELECT tn.field1, tn.field2, DATEADD(DAY, num * 7, @startDate), DATEADD(DAY, num * 7 + 6, @startDate)
FROM dbo.table_name tn
CROSS JOIN cteTally
WHERE
    num BETWEEN 0 AND DATEDIFF(DAY, @startDate, @last_date_to_generate) / 7 - 1
    --AND tn.col_name = 'some_value' AND ...
ORDER BY
    3
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question