Insert Values from One Database Table to Another Database Table in SQL Server

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.    
  4. INSERT INTO dbo.Target_Table(Column1, Column2, Column3)  
  5.    SELECT Column1, Column2, Column3  
  6.    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.    
  3. INSERT INTO dbo.State(State_Name)  
  4.    SELECT State_Name  
  5.    FROM CollegeDb.dbo.State  
  6.    
  7. INSERT INTO dbo.City(State_ID, City_Name)  
  8.    SELECT State_ID, City_Name  
  9.    FROM CollegeDb.dbo.City  

 Output

 Query Execution

That's it. Happy Coding!!

Ebook Download
View all
Learn
View all