-1

I have a create a query which returns a bunch of sql queries , was wondering if those queries can directly be run in one short via a script. Query goes like

with abc as (select  a1, a2 from tableX),
xyz as (Select b1,b2 from tableY)
select a1, 'insert into tableZ values col1= '|| abc.a1||''
from abc , xyz
where abc.a1=xyz.b1;

so can i run all the inserts returned above in one go

1
  • 1
    You don't need dynamic SQL if the only non-fixed piece is a data value. Where you would need dynamic SQL is if you are programmatically determining object names (column lists, table names) or query structure (query blocks, joins), etc. Then you can write a cursor in PL/SQL that loops and uses execute immediate within the loop to execute your dynamic SQL. But as others have said, your example does not present a case where that is needed.
    – Paul W
    Nov 20 at 16:31

2 Answers 2

0

You could use EXECUTE IMMEDIATE in a PL/SQL block but you do not appear to need to dynamically run your query and, instead, can use INSERT INTO ... SELECT ... and use a static SQL query:

INSERT INTO tableZ (col1)
SELECT X.a1
FROM   tableX x
       INNER JOIN tableY y
       ON (x.a1 = y.b1);
-1

Of course with the right syntax

CREATE TABLE tableX(a1 int, a2 int)
CREATE TABLE tableY ( b1 int, b2 int)
CREATE TABLE tableZ(col1 int)
insert into tableZ (col1)
with abc as (select  a1, a2 from tableX),
 xyz as (Select b1,b2 from tableY)
  SELECT abc.a1 as Col1
from abc JOIN  xyz ON abc.a1=xyz.b1;
SELECT * FROM tableZ

fiddle

But you should start using proper JOIN they are since 30 years sql standard.

6
  • "Of course with the right syntax" The generated SQL statement is not valid Oracle synax though.
    – MT0
    Nov 20 at 16:18
  • @MT0 of course it is correct dbfiddle.uk/xYZbyz3p
    – nbk
    Nov 20 at 16:22
  • 2
    The generated statement isn't valid - insert into table tableZ values col1= .... Plus the OP is asking how to run that generated statement - it would have been less confusing if they'd made that clear and used their real query rather than a mangled substitute *8-)
    – Alex Poole
    Nov 20 at 16:28
  • ok i missunderstood teh question and corrected it
    – nbk
    Nov 20 at 17:12
  • Maybe I misunderstood what you are saying, @nbk, but - why CTEs? You'd get the same result with simpler insert into tablez select x.a1 from tablex x join tabley y on x.a1 = y.b1;
    – Littlefoot
    Nov 21 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.