4

Here's what I am trying to do.

This is the select statement

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

Now I want to insert those returned Ids into another table like this:

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

How can I do that ?

3 Answers 3

10

Like this:

insert into tblNpcBattleUsersPokemons
select Id, 1 from tblUsersPokemons where UserId=1 and PokemonPlace='bag'
Sign up to request clarification or add additional context in comments.

2 Comments

Ok what about if i want to show(return selected data from a stored procedure) and also insert the selected data somewhere else. The Insert INTO () SELECT () FROM () it works but i need also to retrieve the collection too. Thanks
Depends what version of SQL Server you have. The later versions have the OUTPUT clause which should work. Otherwise, you would need to use two SQL statements (which isn't normally a problem);
6

This can be done in a single sql call

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

I've used the longhand here because it does not make any assumption about the ordering of columns in the destination table, which can change over time and invalidate your insert statement.

1 Comment

+1 this worked for me. Thanks for posting an alternate answer!!
1

You can insert the set retrieved by a SELECT into another existing table using the INSERT...SELECT syntax.

For example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.