1

I want to create SQL statement (probably a stored procedure) to insert multiple rows in a database table. For the dates in one year depending on the weeks number selected.

For example: if Week number selected = 4

The sql statement should insert the new rows in database table for the current date adding 4 weeks to current date for each row as follows:

CompanyID  DateStart                  ServiceType

101       todayDate                     0091
101       TodayDate + 4weeks            0091
101       TodayDate + 8weeks            0091
101       TodayDate + 12weeks           0091
.               .                          .
.               .                          .
.               .                          .
101       TodayDate + #weeks            0091
            (until this yearEnd only)

** Please NOTE:

1. Before the above script is executed I want to check if there are any records in the same database table for previous year for the company (#101) the serviceType (#0091). If any records exists I want to delete those records.

2. I also want to make sure if for the service type (#0091) for the company(101) already exists in the current year, then I should not insert the new rows in the database table.

Thank you so much for your help for taking time and understanding my question to produce appropriate result.

3
  • Are you on SQL Server 2005 or 2008 ?? You have both tags..... Commented May 25, 2011 at 15:32
  • OK - removed the SQL Server 2008 tag .... Commented May 25, 2011 at 15:36
  • 1
    Hi Marc_S Excellent and very simple to the point. I was thinking I might need to write big query for this logic to implement. I just want to make sure can I write insert satement before the 'Select' stament is executed. Thanks a lot Commented May 25, 2011 at 16:28

1 Answer 1

3

You could try something like this to generate the rows to be inserted:

DECLARE @CurrentYear INT = YEAR(GETDATE())

;WITH DatesToInsert AS
(
    SELECT 
        101 AS 'CompanyID',
        GETDATE() AS 'TodayDate', 
        '0091' AS 'ServiceType'

    UNION ALL

    SELECT 
        101 AS 'CompanyID',
        DATEADD(WEEK, 4, dti.TodayDate) AS 'TodayDate', 
        '0091' AS 'ServiceType'
    FROM      
        DatesToInsert dti
    WHERE
        YEAR(DATEADD(WEEK, 4, dti.TodayDate)) = @CurrentYear
)
SELECT * FROM DatesToInsert

From that CTE (Common Table Expression), you can insert values into a table and check all the other requirements you have. And of course, you can make the number 4 in the DATEADD call configurable, e.g. as the parameter of a stored proc that contains this CTE to handle the inserts.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.