0

I have two tables A and B with 30 columns (same variable names, data for different year), no primary key, almost a million records each.

I want to compare A.X1 with B.X1 (nvarchar8, contains spaces, -, letter and numbers) and insert the outer join results in another table C (with same 30 columns) so I have all rows of A and where B!=A on B.X1).

Example:

Table A

X1   X2   X3 ..... X30
11   E     R .....  G
12   R     4        L
13  S      5        NULL   
14  D      T        NULL

Table B

X1   X2   X3 ..... X30
11   E     R .....  G
12   R     4        L
15  R2     56        NULL   
16  R1      T1        NULL

Resulting table C

X1   X2   X3 ..... X30
11   E     R .....  G
12   R     4        L
13  S      5        NULL   
14  D      T        NULL
15  R2     56        NULL   
16  R1      T1        NULL

How do I do that.

I tried

INSERT INTO C
SELECT *
from A
full outer join B
on A.X1 = B.X1

Error I get

Msg 213, Level 16, State 1, Line 1
Insert Error: Column name or number of supplied values does not match table definition.

I have C created, which is currently empty.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Siftekhar
  • 153
  • 2
  • 7

3 Answers3

1
insert  C
select  *
from    A
union all
select  *
from    B
where  not exists
       (
       select  *
       from    A
       where   X1 = B.X1
       )
Andomar
  • 232,371
  • 49
  • 380
  • 404
0

Your query will not work becasue you are joining the tables and retunring *, with ill results in twice the number of columns that you need. What you really want to do is select everything from table A then APPEND (rather than join) all the records from table B. Appends are achieved by using a UNION. Here is some sample code. Note: never, ever use SELECT *. Addapt the follwing to include the specifically named fields in the correct order.

Also, I am using UNION rather than UNION ALL so that the query automaticlly excludes the records in B that are duplicates of records in A.

SELECT FIELDS...
FROM TABLEA
UNION
SELECT SAME_FIELDS...
FROM TABLEB
Declan_K
  • 6,726
  • 2
  • 19
  • 30
-1
Insert Into TableC
(
  -- List your fields explicitly
)
Select
    -- List all tableA.Fields explicitly
From tableA
Left Outer Join tableB On tableB.X1 = tableA.X1
Where tablB.X1 IS NULL
ganders
  • 7,285
  • 17
  • 66
  • 114