Home

Microsoft SQL Server - Transact-SQL Example: INSERT [INTO]

   

Description

Here are examples of using the INSERT keyword and the optional INTO.

 

 

This is an example of using INSERT INTO to copy records from one table into another:

USE Exercise;
GO

CREATE TABLE Seasonals
(
	SeasonalCode nchar(10),
	Wage money,
	LastName nvarchar(20),
	FirstName nvarchar(20)
);

INSERT INTO Seasonals
VALUES(N'86824', 12.84, N'Chance', N'Julie'),
      (N'84005', 9.52, N'Kaihibu', N'Ayinda');
GO

CREATE TABLE Employees
(
	EmplNbr nchar(10),
	EmployeeName nvarchar(50),
	HourlySalary money
);

INSERT INTO Employees
VALUES(N'22684', N'Ann Keans', 20.52),
      (N'48157', N'Godwin Harrison', 18.75),
      (N'82476', N'Timothy Journ', 21.05),
      (N'15007', N'Ralph Sunny', 15.55);
GO

INSERT INTO Employees
SELECT SeasonalCode, FirstName + N' ' + Lastname, Wage FROM Seasonals;
GO 

Employees

In the same way, you can set a condition to follow when copying the records. Here is an example:

CREATE TABLE Employees
(
	EmployeeNumber nchar(9),
	FirstName nvarchar(20),
	LastName nvarchar(20),
	HourlySalary money,
	[Status] nvarchar(20) null
);
GO
CREATE TABLE ConsideredForPromotion
(
	Number nchar(9),
	FName nvarchar(20),
	LName nvarchar(20),
	Wate money,
	[Type] nvarchar(20)
);
GO
INSERT INTO Employees
VALUES(N'2860-1824', N'Julie', N'Chance', 12.84, N'Full Time'),
      (N'6842-8005', N'Ayinda', N'Kaihibu', 9.52, N'Part Time'),
      (N'9226-2084', N'Ann', N'Keans', 20.52, N'Full Time'),
      (N'2480-8157', N'Godwin', N'Harrison', 18.75, N'Full Time'),
      (N'6824-7006', N'Timothy', N'Journ', 21.05, NULL),
      (N'4150-9075', N'Ralph', N'Sunny', 15.55, N'Part Time');
GO

INSERT INTO ConsideredForPromotion
SELECT EmployeeNumber,
       FirstName,
       LastName,
       HourlySalary,
       [Status]
FROM Employees
WHERE [Status] = N'Full Time';
GO

 

 

 

 


 
 
 
 
 
 
   
 

Home Copyright © 2011 FunctionX.com