Monday, April 26, 2010

Linked Servers and OPENQUERY

So how do you access data from one database to another? (specifically talking about SQL SERVER)

One possible way you can do is to create a Linked Server to the database you want to connect to.
The easiest way to do this is to go to Management Studio, right click on "Server Objects" and click "New Linked Server"

Now on the "New Linked Server" dialog you have 2 ways you can create a Linked Server.
1) Create a Linked Server pointing directly to a SQL SERVER instance
2) Create a Linked Server pointing to several set of supported data sources, this includes OlE DB data sources and also SQL SERVER.

I prefer choosing the 2nd option to create a linked server to SQL SERVER, although I can do this easily by using the first option, the 2nd option gives me the flexibility to easily change my data source without effecting any objects that use it.

For an example, if you use option one, you can access an object (eg an SP) in the other database by using a 4 part name, as following

EXEC LinkedServerName.DataBaseName.SchemaName.ObjectName

so in this case if you change the database name, you need to go change all your objects that uses this Linked Server.

However, if we go for the 2nd option you don't need to, if you use OPENQUERY.

OPENQUERY is a way to execute distibuted queries through a linked server, so for an example, you can write a query like this.

SELECT * FROM OPENQUERY(LinkedServerName, "Select * from countries")

The catch here is that you need to pass in the query as a string to openquery, this means that your execution would be a dynamic SQL.
There is an advantage here as well, now the query executes in the other database, and you can ease up the processing on you database, for this to happen you need to make sure that the query that is passed into OPENQUERY returns a limited filtered set of data, that is the query has a restrictive WHERE clause.

The problem with OPENQUERY is that you won't be able to create your query on the fly with your parameters, nor can you pass in a VARCHAR. The only way you can create your query with your parameters is to create a query that encapsulate the OPENQUERY clause itself, execute the dynamic query and populate a table variable.

Let's hope the next version of SQL SERVER will ease up developer effort on using OPENQUERY.

No comments:

Post a Comment