4

Basically I want to extract id from a table and insert that id in another table with some other data. So the algorythm goes:

foreach id in (select id from table)
{
    insert into table2 values (id,etc,etc);
}

How to perform this function with an SQL query?

1
  • 1
    It is always better to use non-looping SQL. For DB SQL loops are much harder to optimize and analize then SQL select, insert, update, delete statements. The performance difference is very significant. Commented Nov 18, 2011 at 0:03

4 Answers 4

6

Use

insert into table2 
select id, etc, etc from table

instead of for loop.

Here's a helpful article.

Sign up to request clarification or add additional context in comments.

2 Comments

no i just need one value from table i dont need to copy all the table in to the other . i want the ID from table1 and insert it into table2 with some other values for table2 that will remain same in each loop. so only the parameter ID changes after each loop.
@farazali You can use static/hardcoded values where soulcheck has the "etc, etc". e.g. insert into table2 select id, 'my string', '2011-11-12', 5.0, 4 and so on
3
insert into table2 select id,etc,etc from table;

2 Comments

no i just need one value from table i dont need to copy all the table in to the other . i want the ID from table1 and insert it into table2 with some other values for table2 that will remain same in each loop. so only the parameter ID changes after each loop
I don't understand what is wrong. the "etc,etc" part can be anything, and does not come necessarily from table. For instance, you could do: insert into table2 select id,1,2,3 from table
0

The syntax to use is a SQL statement with a select and insert into combination.

Select Into

http://www.w3schools.com/sql/sql_select_into.asp

Comments

0

In SQL Query if you want to use looping then use cursor Pls. check below sample

--DECLARE CURSOR
DECLARE @ID VARCHAR(MAX)

  --READ DATA FROM TABLE TO CURSOR

DECLARE IDCR CURSOR FOR SELECT  id FROM table

OPEN IDCR;

FETCH NEXT FROM IDCR INTO @ID

WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO table2  VALUES (@ID,etc,etc)

FETCH NEXT FROM IDCR INTO @ID
END
CLOSE IDCR;

DEALLOCATE IDCR;

Please check below ref. link https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

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.