使用 T-sql 在数据库表中插入多行
我想创建 SQL 语句(可能是存储过程)来在数据库表中插入多行。对于一年中的日期,取决于所选的周数。
例如: 如果选择的周数 = 4
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)
** 请注意:
1. 在执行上面的脚本之前,我想检查同一个数据库表中是否有上一年的记录 对于公司(#101),服务类型(#0091)。如果存在任何记录,我想删除这些记录。
2. 我还想确保公司(101) 的服务类型(#0091) 在今年已经存在,那么我不应该插入数据库表中的新行。
非常感谢您花时间理解我的问题以产生适当的结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试这样的操作来生成要插入的行:
从该 CTE(通用表表达式)中,您可以将值插入表中并检查您拥有的所有其他要求。当然,您可以将
DATEADD
调用中的数字4
设为可配置,例如作为包含此 CTE 来处理插入的存储过程的参数。You could try something like this to generate the rows to be inserted:
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 theDATEADD
call configurable, e.g. as the parameter of a stored proc that contains this CTE to handle the inserts.