Solved

Inserting records; increment weekly

Posted on 2013-02-05
10
229 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
Comment Utility
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
Comment Utility
cursor?
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
Comment Utility
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
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
Comment Utility
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
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
Comment Utility
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:
ScottPletcher earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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:ScottPletcher
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

762 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now