Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into a table using loop based on another select statement

Tags:

sql

sql-server

I have a select query which returns some IDs.

SELECT GROUP_ID FROM GROUP_REQUEST_MAPPING WHERE REQUEST_TYPE_ID = 1

As a result I get this.

GROUP_ID
6
7
8
9
14

I have to loop through the IDs and then insert that many rows in another table.

INSERT INTO REQ_TASK VALUES(_,_,_,IDs)

How do I do that. I am new to sql. Thanks

like image 365
Jyotirmaya Prusty Avatar asked Oct 28 '25 08:10

Jyotirmaya Prusty


1 Answers

Directly use the constants or parameters with the select like below:

INSERT INTO REQ_TASK VALUES(_,_,_,IDs)
SELECT @param1,@param2,'xyz', GROUP_ID FROM GROUP_REQUEST_MAPPING WHERE REQUEST_TYPE_ID = 1

Here is a small example

 Create table #food
( item varchar(50))

insert into #food values 
('icecream'),
('sandwich'),
('Pasta'),
('FrenchFries'),
('Toast')

--Create another table #food_test

Create table #food_test
( item varchar(50),quantity int)

Insert into #food_test(item,quantity)
select item,10 from #food

Now check the value in #food_test

select * from #food_test
like image 66
Kapil Avatar answered Oct 30 '25 21:10

Kapil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!