SQL Server查询 - 如何将选定的值插入另一个表

Mon*_*RPG 4 t-sql sql-server select insert sql-server-2008-r2

这就是我想要做的.

这是select语句

select Id 
from tblUsersPokemons 
where UserId = 1 and PokemonPlace = 'bag'
Run Code Online (Sandbox Code Playgroud)

现在我想将那些返回的ID插入到另一个表中,如下所示:

foreach all returned Ids
   insert into tblNpcBattleUsersPokemons values (Id, 1)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

RBa*_*ung 10

像这样:

insert into tblNpcBattleUsersPokemons
select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
Run Code Online (Sandbox Code Playgroud)


Nei*_*oss 6

这可以在单个sql调用中完成

insert into tblNpcBattleUsersPokemons (id, [whatever the name of the other column is])
    select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
Run Code Online (Sandbox Code Playgroud)

我在这里使用了longhand,因为它没有对目标表中列的排序做出任何假设,这可能会随着时间的推移而改变并使insert语句无效.