Append table to an existing one: SQL Server

The basic form is:

insert into tableB(col1, col2)
    select col1, col2
    from tableA;

This may not work if, for instance, you have a unique constraint on the columns and the insert violates this constraint.

This assumes that you actually want to add the rows to the table. If you just want to see the results together:

select col1, col2 from tableB union all
select col1, col2 from tableA;

EDIT:

The goal seems to be to add columns one tableB. You can do this by adding the columns and then updating the values:

alter table tableB add col1 . . . ;
alter table tableB add col2 . . . ;

The . . . is the definition of the column.

Then do:

update b
    set col1 = a.col1, col2 = b.col2
    from tableb b join
         tablea a
         on b.joinkey = a.joinkey;

If you don’t have a column for joining, then you have a problem. Tables in SQL are inherently unordered, so there is no way to assign values from a particular row of A to a particular row of B.

Leave a Comment