Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2012 - Insert into linked server table using openquery

I have a linked server Remoteserver containing a table that holds file and folder names from a dir

When I am on the remote server I can run a built in procedure (xp_dirtree) and populate the 'files' table but what i need to do is to run a query from the local SQL server that does this:

  1. Delete all records from the [Files] table on Remoteserver
  2. Insert data that comes from the stored procedure:

    INSERT [Remoteserver].[dbo].[files] (subdirectory,depth,isfile)
       EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;
    
  3. Select the 'subdirectory' column

I tried some things using openquery and i am able to select existing records but unable to do the insert.

Any help is appreciated.

like image 635
Kiran Avatar asked Jan 09 '15 05:01

Kiran


People also ask

Is Openquery faster than linked server?

The OPENQUERY is faster than the linked server because when we use the linked server, the SQL Server breaks the query into local and remote queries. The local queries are executed on the local server, and remote queries will be sent to the remote server.

How do you pass variables in Openquery?

OPENQUERY does not accept variables for its arguments. If you need to build the query dynamically you can use dynamic SQL. Note the declaration of the variable within the query statement (and the assignment of a value with double quotes).

How does Openquery work in SQL Server?

Executes the specified pass-through query on the specified linked server. This server is an OLE DB data source. OPENQUERY can be referenced in the FROM clause of a query as if it were a table name. OPENQUERY can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement.

How do I query a linked server in SQL?

1 Open SQL Server Management Studio, navigate to the Object Explorer pane, and select Server Objects > Linked servers > Providers. 2 Right-click mrOledb. Provider and select Properties. 3 Select allow in process, and then click OK.


1 Answers

Try this

INSERT INTO OPENQUERY([Remoteserver]
    ,'SELECT subdirectory, depth, [file] FROM [RemoteDB].[dbo].[files]')
EXEC master.sys.xp_dirtree '\\fileserver\DBBackup', 1, 1;

OR

INSERT INTO OPENQUERY([Remoteserver]
    ,'SELECT subdirectory,depth, [file] FROM [RemoteDB].[dbo].[files]')
select * from OPENQUERY([another_server_name], 'master.sys.xp_dirtree ''\\fileserver\DBBackup\temp'', 1, 1');

But in general you do not need to use OPENQUERY at all if Fileserver and Remoteserver are accessible from the local machine.

INSERT INTO [Remoteserver].[RemoteDB].[dbo].[files] (subdirectory, depth, isfile)
   EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;
like image 135
Andrey Morozov Avatar answered Sep 18 '22 20:09

Andrey Morozov