cortomaltese_marcof
cortomaltese_marcof

Reputation: 155

dynamically generate sql insert statements from results of a query

I have to generate a series of insert statements based on the results of a query for a db2 and oracle databases. In practice from a query like this

select g.id from SUV_OWNER.gruppi g 
WHERE EXISTS (SELECT 1 FROM SUV_OWNER.GRUPPIRUOLIPROCEDURE grp WHERE grp.gruppoid=g.gruppoid 
AND GRP.RUOLOID = 50)
AND 
G.CHIAVE LIKE 'ANA%';

which generates as output a sequence of numbers not known in advance as

30000  
30001  
.....  

I have to generate for each number an insert statement as

insert into SUV_OWNER.GRUPPIRUOLIPROCEDURE (GRUPPOID, RUOLOID, PROCEDURAID) values  (30000, 141, 7);  
insert into SUV_OWNER.GRUPPIRUOLIPROCEDURE (GRUPPOID, RUOLOID, PROCEDURAID) values  (30001, 141, 7);

I'm a newbie in sql, how can i generate this sequence of inserts ?

Thanks for your help

Upvotes: 2

Views: 1959

Answers (1)

sstan
sstan

Reputation: 36473

It's pretty easy. Just take your existing query, and modify your SELECT to concatenate the INSERT statement with the g.id value.

FYI: || is Oracle's string concatenation operator. I'm not familiar with DB2, but I believe it supports the same syntax for concatenating strings. So the query should work for both databases (I hope).

select 'insert into SUV_OWNER.GRUPPIRUOLIPROCEDURE (GRUPPOID, RUOLOID, PROCEDURAID) values (' || g.id || ', 141, 7);'
from SUV_OWNER.gruppi g 
WHERE EXISTS (
  SELECT 1 
  FROM SUV_OWNER.GRUPPIRUOLIPROCEDURE grp 
  WHERE grp.gruppoid=g.gruppoid 
  AND GRP.RUOLOID = 50)
AND G.CHIAVE LIKE 'ANA%';

Upvotes: 2

Related Questions