Solved

SQL SERVER - does not exist in - Help with sql  insert

Posted on 2014-02-17
3
412 Views
Last Modified: 2014-02-17
Hi..
I have 2 identical tables   A and B. both with an ID

I want to insert the records from B into A that are not in A.

what is the correct SQL syntax

thx
0
Comment
Question by:JElster
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 16

Assisted Solution

by:Surendra Nath
Surendra Nath earned 200 total points
ID: 39865270
try this out

INSERT INTO A
SELECT * FROM B 
WHERE NOT EXISTS ( SELECT 1 FROM A WHERE A.id = B.id)

Open in new window

0
 
LVL 65

Accepted Solution

by:
Jim Horn earned 200 total points
ID: 39865278
Just to be safe...

INSERT INTO A (id, column1, column2, ..., columnN)
SELECT id, column1, column2, ..., columnN
FROM B
   LEFT JOIN A ON B.id = a.id
WHERE a.id IS NULL

The above FROM .. WHERE NOT EXISTS will also work, although I would recommend

WHERE NOT EXISTS ( SELECT id FROM A WHERE A.id = B.id)
0
 
LVL 10

Assisted Solution

by:PadawanDBA
PadawanDBA earned 100 total points
ID: 39865281
assuming the IDs are aligned the following should work...

insert into A
  select
      *
  from
      B as B
           left join A as A on B.ID = A.ID
  where
      A.ID is null;

Open in new window


Edit:
As an addendum, if the ID is an identity, you will have to turn identity insert on and may have to reseed the identity column
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is basically a blog post I wrote recently. I've found that SARGability is poorly understood, and since many people don't read blogs, I figured I'd post it here as an article. SARGable is an adjective in SQL that means that an item can be fou…
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question