Mssql 从其他列中插入多个具有相同 id 的原始数据



你好,我有一个插入查询的问题,我试着解释一下下面:

这是我的表的简化视图 表

表A         表 B
ID/号码   ID
1/0 1 1/1 2 1/2 3 2 2/0 4
2/1        
                    5
2/2                        
    6
3
/0 7
                                         3/1               8
3/2 9
             

所以我已经有了我的查询,谁选择了表 B 的 ID 不在表 A 内

我想将它们插入表 A 中,但如您所见,我需要插入它们 3 次,第一次插入后我的查询不再起作用。

最好的方法是什么?创建视图?一张桌子?还是多次查询?

因此,感谢所有在这里回答的人是我用来解决问题的解决方案:

//Here i get the Missing ID and put them inside temp Table
select ID into #temp_id from TableA rv left outer join TableB lrva on
rv.ID = lrva.ID where 'other Table B attribut'  is null
//Then i insert the values
insert into TableA select ID, 1 from #temp_id;
insert into TableA select ID, 2 from #temp_id;
insert into TableA select ID, 3 from #temp_id;
//Then destroy the temp table
Drop Table #temp_id

请记住,我需要对数字列进行特定处理,就像我在示例中没有命名的其他列一样,这就是为什么我不能只做 +1 或类似的事情。问题的含义只是如何以最简单的方式从其他表中插入多个id,而不是如何在示例中实现这一点作为简单数据。

我想这有效:

CREATE table TABLEA(id int, [number] int)
CREATE table TABLEB (id int)
insert into TABLEA values (1,  0 )
insert into TABLEA values (1,  1 )
insert into TABLEA values (1,  2 )
insert into TABLEA values (2,  0 )
insert into TABLEA values (2,  1 )
insert into TABLEA values (2,  2 )
insert into TABLEA values (3,  0 )
insert into TABLEA values (3,  1 )
insert into TABLEA values (3,  2 )
insert into TABLEB values (1)
insert into TABLEB values (2)
insert into TABLEB values (3)
insert into TABLEB values (4)
insert into TABLEB values (5)
insert into TABLEB values (6)
insert into TABLEB values (7)
insert into TABLEB values (8)
insert into TABLEB values (9)
DECLARE @QUERY VARCHAR(MAX)
DECLARE C CURSOR FOR
select 'INSERT INTO TABLEA VALUES ('+convert(char,id)+',0),('+convert(char,id)+',1),('+convert(char,id)+',2)' from TABLEB where id not in (select id from TABLEA)
OPEN C
FETCH NEXT FROM C INTO @QUERY
WHILE @@FETCH_STATUS=0
BEGIN
EXEC (@QUERY)
FETCH NEXT FROM C INTO @QUERY
END
CLOSE C
DEALLOCATE C
SELECT * FROM TABLEA
id          number
----------- -----------
1           0
1           1
1           2
2           0
2           1
2           2
3           0
3           1
3           2
4           0
4           1
4           2
5           0
5           1
5           2
6           0
6           1
6           2
7           0
7           1
7           2
8           0
8           1
8           2
9           0
9           1
9           2

试试这个:这将给你你想要的,它会给你完全按照你的要求产生笛卡尔值,你可以通过使用WHERE来添加条件来限制数据:

create table #tableA(id int, number int)
create table #tableB(id int)
insert into #tableB values
(1),(2),(3),(4),(5),(6),
(7),(8),(9)
insert into #tableA
select t.id, number
from (values(0),(1),(2)) x (number)
cross apply(select id from #tableB) t
where not exists(select 1 from #tableA A where A.id = t.id)

输出--从 #tableA 中选择 *

id  number
1   0
1   1
1   2
2   0
2   1
2   2
3   0
3   1
3   2
--so on for each ids...

最新更新