Solved

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

Posted on 2014-02-17
3
396 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
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

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

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

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

895 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now