-2

I have three databases in same server which having same kind of tables as below.

City

id -> primary_key
name

Contacts

id -> primary_key
city_id -> foreign_key
name
number

First and second databases having some cities and contacts related to those cities. Now I want to insert all the data from both the databases into third database. So I tried it with import/export database but primary key values are being conflicted.

For city table I can insert data manually as 2 3 cities are there in both the databases but it's not convenient for contacts as contacts are approx 5000. So how can I do it with some easy way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
DD77
  • 776
  • 2
  • 8
  • 25
  • Please do not use tags that do not apply to your question. – John Conde Jul 17 '17 at 11:26
  • Also, at [so] you are expected to try to **write the code yourself**. After **[doing more research](//meta.stackoverflow.com/questions/261592)** if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a [**Minimal, Complete, and Verifiable example**](//stackoverflow.com/help/mcve). I suggest reading [ask] a good question and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour] and read **[this](//meta.stackoverflow.com/questions/347937/)**. – John Conde Jul 17 '17 at 11:26

1 Answers1

0

Use simple INSERT statement (database_name.[schema_name].table)

INSERT [NewDB].[your_schema].[City](Id,Name) 
SELECT id, Name
FROM [OldDB].[your_schema].[City]
where _your where clause_

you can see here: Insert data from db to another db

and here:How to insert table values from one database to another database?

Hasan
  • 296
  • 1
  • 8
  • 23
  • Thank You! it's working but I had to add `SET foreign_key_checks = 0` before and `SET foreign_key_checks = 1` after my insert query – DD77 Jul 18 '17 at 08:38
  • That is always in such copy (repeated copz to a data base): you must deactivate the foreign key checking and when the copy is finished you activate it again normally: such a copy take place one time for all the needed tables. – Hasan Jul 18 '17 at 13:24