Solved

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

Posted on 2014-02-17
3
388 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

     When we have to pass multiple rows of data to SQL Server, the developers either have to send one row at a time or come up with other workarounds to meet requirements like using XML to pass data, which is complex and tedious to use. There is a …
After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

763 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

8 Experts available now in Live!

Get 1:1 Help Now