sql - 插入到 sql server 表中,使用返回超过 1 个值的子查询
问题描述
我有以下表格
表格1
表2
表3
我希望对于条件为真的 table2 中的每个 id,在 table1 中插入 2 行。这些行应该有 table2.id 和 table3.id (对于 table3 中的所有 id)
到目前为止,这是我的脚本。
INSERT INTO table1 (wid, w_check_id)
SELECT (SELECT w.id FROM table2 w WITH(NOLOCK) WHERE w.category_code IN ('004','001')),
id
FROM table3 WITH(NOLOCK)
预期的结果应该是这样的:
表格1
编号 | w_id | w_check_id
1 | 32098 | 1
2 | 32098 | 2
3 | 82459 | 1
4 | 82459 | 2
解决方案
The rows should have the table2.id and all ids in table3
听起来你需要一个交叉连接:
Insert into @T1 (wid,w_check_id)
SELECT w.id,T3.Id
FROM @T2 w
cross JOin @T3 T3
WHERE w.wallet_category_code IN ('004','001')