0

I'm new to PL/SQL. Is it possible to create a given number of tables with identical columns but specific table names inside a while (or for) loop setting the individual table names with the help of string concatenation e.g. No_1, No_2, etc?

My attempt:

DECLARE
  my_num  integer := 1;
  conc char(1);
BEGIN
  WHILE my_num <= 5 LOOP
    select to_char(my_num) into conc from dual;

    Create table No_||conc (dists float);
    my_num :=my_num+1;
  END LOOP;
END;

It does not work. I would be grateful if someone could make this clear for me.

1 Answer 1

3

You need an execute immediate statement to run DDL inside a PL/SQL block, like this:

DECLARE
  my_num  integer := 1;
  conc char(1);
BEGIN
  WHILE my_num <= 5 LOOP

    execute immediate 'create table No_' || my_num || ' (dists float)';

    my_num :=my_num+1;
  END LOOP;
END;

However, I want to point out that Oracle discourages the use of integer and float (in favor of number), and char in favor of varchar2. And I think your code would be more commonly written like this:

BEGIN
  FOR my_num in 1..5 LOOP
    execute immediate 'create table No_' || my_num || ' (dists number)';
  END LOOP;
END;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your clarification! Have a nice day!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.