Solved

Inserting records; increment weekly

Posted on 2013-02-05
10
230 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
 
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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:
ScottPletcher 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:ScottPletcher
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

920 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