3

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

Jyotirmaya Prusty
  • 268
  • 1
  • 8
  • 23

3 Answers3

3

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
Kapil
  • 947
  • 5
  • 10
1

You can use:

INSERT INTO REQ_TASK (col1, ...) 
SELECT GROUP_ID FROM GROUP_REQUEST_MAPPING 
WHERE REQUEST_TYPE_ID = 1;
Arulkumar
  • 12,541
  • 13
  • 48
  • 65
McMurphy
  • 1,063
  • 1
  • 11
  • 35
0

You can directly use your query to insert in another table via insert into statement as

USE MASTER

 Create table GROUP_REQUEST_MAPPING
( GROUP_ID int, REQUEST_TYPE_ID int)

insert into GROUP_REQUEST_MAPPING values 
(6,1),
(7,1),
(8,1),
(9,1),
(10,1)
Create table REQ_TASK (AMOUNT int, IDs int)
SELECT * FROM GROUP_REQUEST_MAPPING
SELECT * FROM REQ_TASK

INSERT INTO REQ_TASK (AMOUNT,IDs)
SELECT 10, GROUP_ID FROM GROUP_REQUEST_MAPPING WHERE REQUEST_TYPE_ID = 1

SELECT * FROM REQ_TASK

DROP TABLE REQ_TASK
DROP TABLE GROUP_REQUEST_MAPPING

https://www.w3schools.com/sql/sql_insert_into_select.asp

Ajay2707
  • 5,624
  • 6
  • 38
  • 56