Solved

SQL server indentify then insert missing rows from database to another

Posted on 2011-09-12
5
211 Views
Last Modified: 2012-08-13
There are 9031 ids in one table that i need to find the ROWS with those ids from another table then insert those rows into another table..


What would be the best way to do this without manullay typing out 9031 times?
0
Comment
Question by:wilko100
  • 2
  • 2
5 Comments
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 400 total points
ID: 36524266
Hi.

So it sounds like you have table A (9031 ids), table B (9031 ids), and then table C (missing some ids and needs updating) -- that correct?

If so, then you can do this:

INSERT INTO C({column list})
SELECT {column list}
FROM A
JOIN B ON A.id = B.id
/* check for those id values that are not in C yet */
WHERE NOT EXISTS (
   SELECT 1
   FROM C
   /* or whatever unique key(s) connect C to B|A */
   WHERE C.id = A.id 
)
;

Open in new window


Hope that helps!
0
 
LVL 23

Assisted Solution

by:Racim BOUDJAKDJI
Racim BOUDJAKDJI earned 100 total points
ID: 36524294
Additionally to the above comment, don't forget to set the IDENTITY to OFF before attempting to insert.
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 36524316
Thanks, Racimo! Good point. wilko100, if you need anything else, just let us know. Between Racimo and I, we should be able to help you through understanding what you need to do.
0
 

Author Comment

by:wilko100
ID: 36525524
Cheers, i'll try that
0
 

Author Closing Comment

by:wilko100
ID: 36937837
Sorry for the delay responding, just got a pre prod enviorment setup. Works a treat. Dont think i would of done it with the help

 Thanks for the advice
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

705 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

18 Experts available now in Live!

Get 1:1 Help Now