将项目添加到另一个项目时插入新行 table SQL

Insert new rows when item is added to another table SQL

必须 tables。一维 table 包含项目,一个事实 table 包含项目、值和时间段(月)。

希望在我的事实 table 中添加 12 个新行 pr 项目 ID,当一个新项目被添加到维度 table 时。 12 行应该是接下来的 12 个月。 (总是当前月份之后的月份)

我知道添加新行时应该是创建触发器,那部分没问题。 我遇到的问题是如何编写可以与触发器一起使用的 SQL 语句来完成这项工作。我已经在 INSERT INTO 上尝试了一些版本,但我没有足够的经验知道必须写这个语句。

示例:项目 2 已添加到 dim table。

project status
1 A
2 B

然后创建一个触发器,在我的事实中添加这 12 个新行table

project status Period Value
2 B 6/1/2021 NULL
2 B 7/1/2021 NULL
2 B 8/1/2021 NULL
2 B 9/1/2021 NULL
2 B 10/1/2021 NULL
2 B 11/1/2021 NULL
2 B 12/1/2021 NULL
2 B 1/1/2022 NULL
2 B 2/1/2022 NULL
2 B 3/1/2022 NULL
2 B 4/1/2022 NULL
2 B 5/1/2022 NULL

关于如何写这个声明有什么建议吗?

非常感谢!

您可以使用 CTE 即时生成数字列表,然后无条件加入 inserted table 以生成您的行:

with months as (
    select top (12)  Row_Number() over(order by (select null)) as m from sys.sysobjects
)
select i.Project, i.Status,
  DateAdd(month,m,DateAdd(month, DateDiff(month, 0, GetDate()), 0)) as Period
from months join inserted i on 1=1

这是一种方法:

 --==== Test 'inserted' table
Declare @inserted Table (Project int, Status char(1));
 Insert Into @inserted (Project, Status)
 Values (1, 'A'), (2, 'B');

 --==== Test 'facttable'
Declare @factTable Table (Project int, Status char(1), Period date, Value varchar(50));

 --==== Example code for trigger
   With periods (Period)
     As (
 Select dateadd(month, p.num, dateadd(month, datediff(month, 0, getdate()), 0))
   From (Values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12) ) As p(num)
        )
 Insert Into @factTable (Project, [Status], [Period], [Value])
 Select i.Project
      , i.[Status]
      , p.[Period]
      , Value = Null
   From periods                 p
  Cross Join @inserted          i;

 --==== Show resulting fact table
 Select *
   From @factTable;

触发器的示例代码是解决方案,并假定您不会有重复的项目条目。我们不必使用 row_number 生成数字 - 只需使用 VALUES 并指定 1 到 12.