Insert multiple rows in Database table using T-sql
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 underst开发者_如何学编程anding my question to produce appropriate result.
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.
精彩评论