Blog

Copy data from one table to another table using a single query

SQL / Uncategorized

Copy data from one table to another table using a single query

  1. Create a table as Departments with identity column and insert dummy data into it
				
					CREATE TABLE [dbo].[Departments](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[DepartmentName] varchar(20) NULL,
 CONSTRAINT [PK_Departments] PRIMARY KEY CLUSTERED (Id))
 
 INSERT INTO Departments (DepartmentName) values ('IT') 
 INSERT INTO Departments (DepartmentName) values ('ECE')
 INSERT INTO Departments (DepartmentName) values ('CS')
 INSERT INTO Departments (DepartmentName) values ('MEC')
				
			

2. Create DepartmentsCopy table where all the records from the Department table will be inserted

				
					CREATE TABLE [dbo].[DepartmentsCopy](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[DepartmentName] varchar(20) NULL,
 CONSTRAINT [PK_DepartmentsCopy] PRIMARY KEY CLUSTERED (Id))
				
			

3. Query to copy data from Departments table to DepartmentsCopy table

				
					 INSERT INTO DepartmentsCopy (DepartmentName)
 SELECT DepartmentName FROM Departments
				
			

All the records from the Departments table are now copied into the DepartmentsCopy table.

maxcoach-shape-01
maxcoach-shape-02

Free 10 Days

Master Course Invest On Self Now

Subscribe & Get Your Bonus!
Your infomation will never be shared with any third party