Loop in SQL query

Basically, I want to extract id from a table and paste this id into another table with some other data. So the algorithm goes:

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

How to execute this function with SQL query?

+4
source share
4 answers

Use

 insert into table2 select id, etc, etc from table 

instead of a loop.

Here is a helpful article.

+6
source
 insert into table2 select id,etc,etc from table; 
+3
source

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

Choose "B"

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

0
source

In SQL Query, if you want to use a loop, use the Pls cursor. 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. link https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

0
source

Source: https://habr.com/ru/post/1381818/


All Articles