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.
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:
- 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).
- 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
- Running the above query will open file explorer. Select all files and save the file as insert query.txt.
- Use that file to add records in destination server.