2012-12-10 37 views
4

以下是我正在嘗試執行的操作。SQL Server查詢 - 如何將選定的值插入到另一個表中

這是select語句

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

現在我想插入那些返回ID添加到另一個表是這樣的:

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

我怎樣才能做到這一點?

回答

10

像這樣:

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

好吧如果我想顯示(從存儲過程返回選定的數據),並將選定的數據插入其他地方怎麼樣。 Insert INTO()SELECT()FROM()它的工作原理,但我也需要檢索集合。 謝謝 – JohnnyJaxs

+0

取決於您擁有的SQL Server版本。後來的版本有'OUTPUT'條款應該工作。否則,您將需要使用兩個SQL語句(這通常不是問題); – RBarryYoung

1

可以插入使用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'; 
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' 

我在這裏使用的速記,因爲它沒有對列進行排序的任何假設進行目標表,它可以隨時間變化並使插入語句無效。

+0

+1這爲我工作。感謝您發佈備用答案! – ckpepper02

相關問題