Ask the Expert

Copying rows between tables with mismatched columns

I am trying to copy data from TableA into a history/archive table, TableB. TableA and TableB are exactly alike, except TableB contains a field "Archive_ID" which does not exist in TableA. How do I get past this? I tried the following statement:
INSERT INTO TABLEB
SELECT *
FROM TABLEA
But because of the extra field in B, it won't work.

    Requires Free Membership to View

In an INSERT INTO... SELECT statement, the columns in the SELECT clause must match the number and the data types (loosely) of the columns in the INSERT INTO clause. To illustrate, here are two sample tables:

create table TableA
( Stuff numeric(5),
  MoreStuff varchar(30)
);

create table TableB
( Stuff numeric(5),
  MoreStuff varchar(30),
  ExtraColumn numeric(5)
);
To populate TableB with data from TableA, either of the following INSERT statements will do the trick:
insert into TableB (Stuff, MoreStuff)
  select * from TableA;
  
insert into TableB
  select Stuff, MoreStuff, null from TableA;

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 April 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: