Pages

Thursday 10 January 2013

Query to use top keyword clause with insert statement in sql server

Before write query to use top keyword or clause with insert statement we need to design table UserInformation in database like as shown below

Column Name
Data Type
Allow Nulls
UserId
Int (set Identity=true)
No
UserName
varchar(50)
Yes
Location
Varchar(50)
Yes
Here we can use Top keyword or clause with insert statement in two different ways
First Method
Syntax to use top keyword with insert statement
INSERT INTO Table1
SELECT TOP (N) Column1, Column2 FROM Table2
Example
-- Declare temp table
CREATE TABLE #temp(name VARCHAR(50),place VARCHAR(50))
INSERT INTO #temp(name,place) VALUES('test','Chennai')
INSERT INTO #temp(name,place) VALUES('test1','Hyderabad')
INSERT INTO #temp(name,place) VALUES('test2','Guntur')
-- insert temp table values into UserInformation table
INSERT INTO UserInformation(UserName,Location)
SELECT TOP 2 name,place FROM #temp
DROP TABLE #temp
Once we run above query our table UserInformation will contain data like as shown below

Output

Second Method

Syntax to use top keyword with insert statement
INSERT TOP(N) INTO Table1
SELECT Column1,Column2 FROM Table2
Example
-- Declare temp table
CREATE TABLE #temp(name VARCHAR(50),place VARCHAR(50))
INSERT INTO #temp(name,place) VALUES('test','Chennai')
INSERT INTO #temp(name,place) VALUES('test1','Hyderabad')
INSERT INTO #temp(name,place) VALUES('test2','Guntur')
-- insert temp table values into UserInformation table
INSERT TOP(2) INTO UserInformation(UserName,Location)
SELECT name,place FROM #temp
DROP TABLE #temp
Once we run above query our table UserInformation will contain data like as shown below

Output

By using above two methods we can insert data into tables with top keyword in SQL Server

No comments:

Post a Comment