1110
1110

Reputation: 6829

How to perform insert for each selected row from database

I am trying to make stored procedure that:
- Get list of int rows

select ItemId from Items -- this returns: 1,2,3,4,5,6

So it's not one column. Sorry for confusion :(

Upvotes: 3

Views: 7520

Answers (4)

StuartLC
StuartLC

Reputation: 107247

Edit : Assuming that the table [table] already exists, and if User is a constant, then do like so:

INSERT INTO [table](UserId, ItemIdInAnotherTable) 
   SELECT 13879, ItemId 
   FROM Items;

If UserId comes from another table entirely, you'll need to figure out what relationship you need between UserId and ItemId. For instance, if all users are linked to all items, then it is:

INSERT INTO [table](UserId, ItemIdInAnotherTable) 
   SELECT u.UserId, i.ItemId 
   FROM Items i CROSS JOIN Users u;

If table [table] does NOT already exist, then you can use SELECT INTO, and specify a new table name (e.g. a #temp table stored in tempdb)

SELECT u.UserId, i.ItemId 
   INTO #tmpNewTable
   FROM Items i CROSS JOIN Users u;

The columns in the newly created table will have the names UserId and ItemId and have the same types.

Upvotes: 6

John Woo
John Woo

Reputation: 263723

use INSERT INTO..SELECT statement

INSERT INTO ItemIdInAnotherTable (ItemId)
SELECT ItemId 
FROM   Items

Upvotes: 0

dan1111
dan1111

Reputation: 6566

That is exactly what a normal insert command does. Just do something like this:

insert into Table (ItemID) 
    select ItemID from Items;

Upvotes: 0

Danielle Paquette-Harvey
Danielle Paquette-Harvey

Reputation: 1791

Looks simple to me:

 INSERT INTO ItemIdInAnotherTable (ItemId)
 SELECT ItemId from Items

Upvotes: 1

Related Questions