【问题标题】:SQL Server query - how to insert selected values into another tableSQL Server 查询 - 如何将选定的值插入另一个表
【发布时间】:2012-12-10 22:25:25
【问题描述】:

这就是我想要做的。

这是选择语句

select Id 
from tblUsersPokemons 
where UserId = 1 and PokemonPlace = 'bag'

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

foreach all returned Ids
   insert into tblNpcBattleUsersPokemons values (Id, 1)

我该怎么做?

【问题讨论】:

    标签: sql-server tsql select insert sql-server-2008-r2


    【解决方案1】:

    像这样:

    insert into tblNpcBattleUsersPokemons
    select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
    

    【讨论】:

    • 好吧,如果我想显示(从存储过程返回选定的数据)并将选定的数据插入其他地方。 Insert INTO () SELECT () FROM () 它可以工作,但我也需要检索集合。谢谢
    • 取决于您拥有的 SQL Server 版本。更高版本有 OUTPUT 子句应该可以工作。否则,您将需要使用两个 SQL 语句(这通常不是问题);
    【解决方案2】:

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

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

    我在这里使用了速记,因为它不对目标表中列的顺序做出任何假设,这可能会随着时间的推移而改变并使您的插入语句无效。

    【讨论】:

    • +1 这对我有用。感谢您发布替代答案!
    【解决方案3】:

    您可以使用 INSERT...SELECT 语法将 SELECT 检索到的集合插入到另一个现有表中。

    例如:

    INSERT INTO tblNpcBattleUsersPokemons (Id, Val)  -- not sure what the second column name was 
    SELECT Id FROM tblUsersPokemons WHERE UserID = 1 and PokemonPlace='bag';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2020-09-03
      • 2022-01-24
      • 1970-01-01
      • 2018-07-27
      • 2018-05-05
      相关资源
      最近更新 更多