Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append table to an existing one: SQL Server

I have a table A with two columns that I want to append to another table B, how can I do that? They have the exact same rows. Software is SQL Server 2012.

EDIT (attempted code from comment):

INSERT INTO B_table([Column 0], [Column 1])
    SELECT [Column 0], [Column 1]
    FROM [dbo].[A] ;
like image 697
npereira Avatar asked Apr 26 '14 21:04

npereira


People also ask

How do you append data to an existing table in SQL Server?

On the Home tab, in the View group, click View, and then click Design View. On the Design tab, in the Query Type group, click Append. The Append dialog box appears. Next, you specify whether to append records to a table in the current database, or to a table in a different database.

How do I add data to an existing table?

INSERT INTO Syntax Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

How do I combine tables into one in SQL?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);

How do I insert a table at the end of another table?

create table x as select a, b, c from table1 union all select a, b, c from table2; If you want to "append" the values onto the first table, use insert : insert into table1 (a, b, c) select a, b, c from table2; Note that tables in SQL represent unordered sets.


2 Answers

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.

like image 78
Gordon Linoff Avatar answered Sep 18 '22 13:09

Gordon Linoff


Try this:

INSERT INTO tbl1 SELECT * FROM tbl2;
like image 45
Chong Lip Phang Avatar answered Sep 21 '22 13:09

Chong Lip Phang