简体   繁体   English

使用 T-sql 在数据库表中插入多行

[英]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.我想创建 SQL 语句(可能是存储过程)以在数据库表中插入多行。 For the dates in one year depending on the weeks number selected.一年中的日期取决于所选的周数。

For example: if Week number selected = 4例如:如果选择的周数 = 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: sql 语句应在数据库表中插入当前日期的新行,为每行添加 4 周到当前日期,如下所示:

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). 1.在执行上述脚本之前,我想检查公司(#101)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. 2. 我还想确定公司(101)的服务类型(#0091)是否在当年已经存在,那么我不应该在数据库表中插入新行。

Thank you so much for your help for taking time and understanding 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.通过该 CTE(通用表表达式),您可以将值插入表中并检查您拥有的所有其他要求。 And of course, you can make the number 4 in the DATEADD call configurable, eg as the parameter of a stored proc that contains this CTE to handle the inserts.当然,您可以使DATEADD调用中的数字4可配置,例如作为包含此 CTE 以处理插入的存储过程的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM