RSS
 

SQL Import Export from linked server

07 Oct
There is always a need to import/export tables or data from different database. The common scenario is when you need that data to your local database that is in your live database.
For this purpose, many techniques are available, but my technique is simple and modifiable as it takes every table from linked server and makes a query against that and that query can be changeable by you. (e.g you can specify where clause as well).

So first of all you will need to know from which database you want to import and to which it should be exported to.
You will need to link target database server if both database are not in the same servers. To link follow the tutorial given in below link:
http://msdn.microsoft.com/en-us/library/aa259589%28SQL.80%29.aspx.

Now use below query in your source database to get queries that will import data and/or tables

To Import both tables and data

  DECLARE @count INT, @NoOfTables INT, @table VARCHAR(500),@fullquery VARCHAR(5000)
  SET @count = 0
  SET @NoOfTables = (SELECT COUNT(table_name) FROM [SERVER_IP].[DATABASE_NAME].INFORMATION_SCHEMA.TABLES)
  WHILE (@count < @NoOfTables)
  BEGIN
  SET @count = @count + 1
  SELECT @table = TABLE_NAME  FROM  (  SELECT TABLE_NAME, ROW_NUMBER() OVER ( ORDER BY TABLE_NAME DESC ) AS row
								FROM [SERVER_IP].[DATABASE_NAME].INFORMATION_SCHEMA.TABLES
                            ) t
                    WHERE   t.row IN ( @count )
   SET @fullquery = ' SELECT * INTO '+@table+' FROM [SERVER_IP].[DATABASE_NAME].dbo.'+@table
   PRINT @fullquery
  END

Change server_ip, database_name variables in above query according to your server_name, database_name.
Copy the result of above query and run that query to import all tables and data.

To import data only, change SELECT query to INSERT query.
You can change the query to what ever your requirements (use where clause to filter data etc).

 
 

Tags: , ,

Leave a Reply

 

 
 
 
Improve Your Life, Go The myEASY Way™