views:

77

answers:

2

I have to query two different servers from a dynamically built query.

It basically gets data from one server, treats it, and inserts it into another server.

The only problem is I have to be sure it works for both situations: If both the source and destination databases are on the same server, and if they're not.

I understand the concept of using Linked Servers in SQL Server, but I cannot think of a way to consider both alternatives, same server and different servers.

A little help?

+1  A: 

Use a fully qualified table name for both tables (local and remote)

SELECT * FROM SERVER.DATABASE.SCHEMA.TABLE

Germ
You dont need two linked servers just one. As long as you use the Server.Database.Schema.Table notation you will only Need a linked server to the remote server
John Hartsock
Thanks John Hartsock
Germ
+4  A: 

Two linked servers are not necessary... just one per server. Example

PhysicalServerA
   SQLServerA
      DatabaseA
      DatabaseB
   LinkedSQLServerB  // A linked server to SQL Server B

PhysicalServerB
   SQLServerB
      DatabaseC
      DatabaseD
   LinkedSQLServerA  // A linked Server to SQL Server A

Now Server A can have queries to itself like:

SELECT * FROM SQLServerA.DatabaseA.dbo.TableName

And queries to LinkedSQLServerB like

SELECT * FROM SQLServerB.DatabaseC.dbo.TableName

Now Server B can have queries to itself like:

SELECT * FROM SQLServerB.DatabaseC.dbo.TableName

And queries to LinkedSQLServerA like

SELECT * FROM SQLServerA.DatabaseA.dbo.TableName
John Hartsock
Perhaps I didn't understand the concept of using linked servers so well. But anyway, before I post this here, I tried using the fully qualified name of my local server IN my local server, and it didn't work, which made me think that that kind of syntax was only allowed for linked servers, not local. Your answer was very clear though. Thanks a lot!
Felipe Fiali