Solved

Inserting records; increment weekly

Posted on 2013-02-05
10
236 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Stressed Out?

Watch some penguins on the livecam!

 
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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

724 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