根据表B中的Row_Num动态插入到表A中

时间:2020-11-08 18:31:14

标签: sql sql-server tsql sql-insert

我将一些数据压缩到TableB中,如下所示:

+========+==========+=========+
| AreaID | AreaName | Row_Num | 
+========+==========+=========+
|   506  | BC-VanW  |    1    |
+--------+----------+---------+
|   3899 | BC-VicS  |    2    |
+--------+----------+---------+
|   1253 | AB-CalW  |    3    |
+--------+----------+---------+

共有2000个唯一的行,Row_Num从1到2000,并且此表中的每个AreaID也是自然唯一的。

我现在要插入具有以下各列的空白表TableA:

+========+==========+=========+============+===========+
| AreaID | StartDT  |  EndDT  | MarketCode |Allocation |
+========+==========+=========+============+===========+

我要使用的插入语句是重复除AreaID以外的所有内容

我早些时候尝试过一些事情,这是对我所拥有的东西的基本观察,我希望Stackoverflow可以帮助我扩展:

DECLARE @AreaID NVARCHAR(4)
SET @AreaID = (SELECT AreaID FROM TableB WHERE Row_Num = 1)

DECLARE @Sql NVARCHAR(MAX)

SET @Sql = N'                   
INSERT INTO TableA (AreaID, StartDt, EndDt, MarketCode, Allocation) VALUES ('+@AreaID+', ''2020-11-01 00:00:00.000'', ''2049-12-31 00:00:00.000'' , 31 , 25.00);
INSERT INTO TableA (AreaID, StartDt, EndDt, MarketCode, Allocation) VALUES ('+@AreaID+', ''2020-11-01 00:00:00.000'', ''2049-12-31 00:00:00.000'' , 38 , 60.00);
INSERT INTO TableA (AreaID, StartDt, EndDt, MarketCode, Allocation) VALUES ('+@AreaID+', ''2020-11-01 00:00:00.000'', ''2049-12-31 00:00:00.000'' , 39 , 15.00);
'
EXEC sp_executesql @Sql
GO

在这里,我希望它一次又一次地“循环”遍历Row_Nums,并运行上面的完整插入查询,最终对所有2000个Row_Nums执行此操作。

当然,如果有更有效的方法,请告诉我,我会看看。

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为您想使用固定值列表进行交叉连接:

INSERT INTO TableA (AreaID, StartDt, EndDt, MarketCode, Allocation)
SELECT b.AreaID, x.*
FROM tableB b
CROSS APPLY (VALUES 
    ('2020-11-01 00:00:00.000', '2049-12-31 00:00:00.000', 31, 25.00),
    ('2020-11-01 00:00:00.000', '2049-12-31 00:00:00.000', 38, 60.00),
    ('2020-11-01 00:00:00.000', '2049-12-31 00:00:00.000', 39, 15.00)
) x(StartDt, EndDt, MarketCode, Allocation)

如果日期范围始终相同,则可以稍微简化一下:

INSERT INTO TableA (AreaID, StartDt, EndDt, MarketCode, Allocation)
SELECT b.AreaID, '2020-11-01 00:00:00.000', '2049-12-31 00:00:00.000', x.*
FROM tableB b
CROSS APPLY (VALUES 
    (31 , 25.00),
    (38 , 60.00),
    (39 , 15.00)
) x(MarketCode, Allocation)