Q

Creating multiple rows from a group of columns

A master record stores the rolling balances for the next thirty days. I need to store these rolling balances as individual records in a detail table. How can I achieve this in PL/SQL, i.e. one record of the master table gets converted to 30 records in detail table?

I suppose it might be possible to do this with PL/SQL code such as

BEGIN 
  X := 1; 
  WHILE (X < 31) 
  LOOP 
    insert into detail (nextday, balance)
       select X, ??(X) from master;
    X := X + 1; 
  END LOOP; 
END;

... assuming you have some way (denoted by "??" above) of accessing the 30 fields as though they were elements of an array. I think you can do this in SQL-99 but it would require that the table was defined that way, and that your database supports the array structure. More likely is that the table has discretely named columns, such as balance1, balance2, ... balance30.

The obvious solution is simply to code 30 INSERT statements instead of a loop --

insert into detail (nextday, balance)
    select 1, balance1 from master;
insert into detail (nextday, balance)
    select 2, balance2 from master;
 ...
insert into detail (nextday, balance)
    select 30, balance30 from master;

With cut and paste in text editors, this is probably the easiest way to go.

For More Information

  • What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
  • The Best SQL Web Links: tips, tutorials, scripts, and more.
  • Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
  • Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
  • Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

This was first published in March 2002
This Content Component encountered an error

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close