Skip to content
Advertisement

How to use Oracle PL/SQL to create ten similar tables from a given Oracle source table

I have data in one table in a oracle database and I want to “split” this table in SQLplus into ten tables based on the content of one column.

Source table is all_data with columns:

kind, time_period, amount

kind is the row to split on: the value of kind In each row is exactly one of ten different names “peter”, “maria”, “eric”, etc…

Now I want to create ten tables, one for each name. The first table for name “peter” would be created manually in SQL as:

How can I use PL/SQL to create all ten tables peter_data, maria_data, eric_data, etc.?


I tried:

but this gives understandably the error “PLS-00103: Encountered the symbol “CREATE”…

Advertisement

Answer

You just need to wrap your DDL statement in a string and call EXECUTE IMMEDIATE:

(and remove p. as you didn’t define the alias p anywhere.)

Then, if you have the table:

Then you get the tables:

KIND  | TIME_PERIOD         | AMOUNT_PETER
:---- | :------------------ | -----------:
peter | 2020-01-01 00:00:00 |           23
KIND  | TIME_PERIOD         | AMOUNT_MARIA
:---- | :------------------ | -----------:
maria | 2020-02-01 00:00:00 |           42
KIND | TIME_PERIOD         | AMOUNT_ERIC
:--- | :------------------ | ----------:
eric | 2020-03-01 00:00:00 |          11

db<>fiddle here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement