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
				
			

Please comment about how we can enhance our blog posts and please share the post so that dotnercoaching can be more accessible and you become a part of our mission to spread free knowledge to make a better future.