Tag Archives: insert

Generate insert scripts from a result set of SQLserver table

Requirement:
We have a table called employee which contains two columns eno, esal. The table contains ten records.
We are supposed to create a similar table with the same values in other server/database. We can create the same table by using the same CREATE table definition. Using the below method we can generate insert scripts which we can run in the destination, to add data rows. This method uses the concept of cursors.
Method:
Employee table has the following definition:

CREATE TABLE [dbo].[employee](
[eno] [int] NULL,
[esal] [int] NULL
)

Both the employee number, and salary are integers.
Below steps need to be executed in the source server/Database:

  1. Click on Results to File icon in the SQL Editor menu in Management Studio. This can be used to generate all the insert scripts in a text file. Shortcut to do this is (Ctrl+ Shift+ F).
  2. Run the below cursor query:


DECLARE @eno INT,@esal INT
DECLARE insertquery CURSOR FOR
SELECT eno,esal FROM empsalary
OPEN insertquery
FETCH NEXT FROM insertquery INTO @eno,@esal
WHILE @@FETCH_STATUS=0
BEGIN
PRINT 'insert INTO empsalary values('+CONVERT(VARCHAR,@eno)+','+CONVERT(VARCHAR,@esal)+')'
FETCH NEXT FROM insertquery INTO @eno,@esal
END
CLOSE insertquery
DEALLOCATE insertquery

  1. Running the above query will open file explorer. Select all files and save the file as insert query.txt.
  2. Use that file to add records in destination server.