使用 SELECT 和数组插入多行

INSERT multiple rows with SELECT and an array

在EXCEL/VBA我可以通过编程摆脱雷雨,但在SQL我还是个新手。很抱歉,经过大量谷歌搜索后,我只能找到一个解决方案,我认为最终会非常简单,只是没有绕过它。

我需要创建一个 INSERT 脚本以在 3 列中添加多行 table。一个简单的插入将是:

INSERT INTO table VALUES(StoreId, ItemID, 27)

第一个障碍是对不同 table 中的每个 StoreID 动态重复此操作。我认为变成这样:

INSERT INTO table 
SELECT (SELECT StoreID FROM Directory.Divisions), ItemID, 27)

如果这实际上是正确的并且可以有效地为每个商店创建 50-60 行,那么我就快完成了。问题是 ItemID。这实际上是我想手动输入的一组 ItemID。因此,如果有 50 家商店和 3 个 ItemID,它将输入 150 行。类似于:

ItemID = (123,456,789,246,135)

那么如何合并这两个想法呢?从另一个 table 中提取 StoreID,为第二个参数输入项目数组,最后是我的硬编码 27。 50 家商店和 10 件商品应创建 500 行。提前致谢。

您可以使用into插入目标table。要生成 itemid,您必须将 union all 与您的值一起使用,并在 divisions table 上使用 cross join

select 
d.storeid, 
x.itemid, 
27 as somecolumn
into targettablename
from Directory.Divisions d
cross join (select 123 as itemid union all select 456 union all select 789...) x 

编辑:如果 table 到 insert 尚未创建,则应在插入数据之前创建它。

create table targettable as (store_id varchar(20), item_id varchar(20), 
                             somecolumn int);

insert into targettable (store_id, item_id, somecolumn)
select 
d.storeid, 
x.itemid, 
27
from Directory.Divisions d
cross join (select 123 as itemid union all select 456 union all select 789...) x 

首先,您需要某种 table 中的项目 ID 数组。永久 table、table 变量或临时 table。例如使用一个临时的table,你用一个哈希符号作为前缀:

CREATE TABLE #ItemIds (item_id int)
INSERT INTO #ItemIds VALUES (1)
INSERT INTO #ItemIds VALUES (2)
...
INSERT INTO #ItemIds VALUES (10)

那么这应该可以解决问题:

INSERT INTO table
SELECT StoreId, item_Id, 27
FROM Directory.Divisions, #ItemIds

SELECT 中的结果集将被插入到 'table' 中。这是笛卡尔连接的示例。因为没有连接条件,所以 Directory.Divisions 中的每一行都连接到 #ItemIds 中的每一行。因此,如果您有 50 家商店和 10 件商品,则将产生 50 x 10 = 500 行。

您可以为项目 ID 声明 table 变量,并使用 CROSS JOIN 将部门记录乘以项目:http://sqlfiddle.com/#!3/99438/1

create table Divisions(StoreId int)
insert into Divisions values (1), (2), (3)

declare @items table(ItemID int)
insert into @items values (5), (6), (7)

-- insert into target(stireid, itemid, otherColumn)
select d.StoreId, i.ItemID, 27
from Divisions d 
cross join @items i