Introduction

Recently, I was working on the database and there is the situation in which I have to insert the values from one database table to the another database table.

Well, if the table have 2 or 3 values then we can write the Insert Query to insert the values in the table but suppose if there are too many values, then? The same thing happened to me. I have two tables in the database named State and City. There are 25 records in State and 590 records in the City table.

I got the solution to do this.

Solution

The structure of the Query is as follows:

  1. USE Target_Database
  2. GO
  3. INSERT INTO dbo.Target_Table(Column1, Column2, Column3)
  4. SELECT Column1, Column2, Column3
  5. FROM Source_Database.dbo.Source_Table

I have Converted this to the following query:

I have to insert values in two different tables:

  1. Use Country
  2. INSERT INTO dbo.State(State_Name)
  3. SELECT State_Name
  4. FROM CollegeDb.dbo.State
  5. INSERT INTO dbo.City(State_ID, City_Name)
  6. SELECT State_ID, City_Name
  7. FROM CollegeDb.dbo.City

Output

Query Execution

That's it. Happy Coding!!