0

I have a table A

col-PK  col2  col3   col4
1       a      aa     aaa
2       b      bb     bbb

I have created a new table B with three columns only

col-PKB  colOne  ColTwo  

I want below as the Final Output

Table A

col-PK  col2  col3   col4
1       a      aa     aaa
2       b      bb     bbb

Table B

col-PKB  colOne  ColTwo  
1       a       aa     
2       b       bb 

Solution I looked into SO LINK. But I think I need to use select statement as I have multiple columns to copy. Please guide me here. I am lost.

Community
  • 1
  • 1
Unbreakable
  • 7,776
  • 24
  • 90
  • 171

2 Answers2

1

You can use INSERT INTO with a SELECT-query of the columns you want to add:

INSERT INTO tableB (col-PKB, colOne, ColTwo)
  SELECT
    col-PK,
    col2,
    col3
  FROM tableA;
mxlse
  • 2,654
  • 17
  • 31
  • I checked the documentation and there is one SELECT INTO clause. Is that not what I need. Just wondering. – Unbreakable Jan 27 '17 at 16:07
  • Of course you can also use `SELECT col-PK, col2, col3 INTO tableB FROM tableA`. But this creates a new tableB. The new table will be created with the column-names and types as defined in the `SELECT` statement. You can apply new names using the `AS` clause. But if you already created one like in your question, use `INSERT INTO`. – mxlse Jan 27 '17 at 16:10
  • I already have the table with all the columns created into it. So I guess I am better off with your original answer. Thank you so much! – Unbreakable Jan 27 '17 at 16:14
  • Accepting the answer would be appreciated then, – mxlse Jan 27 '17 at 16:47
1

Try like this:

INSERT INTO table (column)
  SELECT a_column 
  FROM a_table

In your case,

INSERT INTO tableB (
col-PKB, colOne, ColTwo
)
SELECT col-PK, col2, col3 
FROM tableA
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45