views:

94

answers:

2

I have the same query in a stored procedure that needs to be executed on different servers and databases according to parameters.

How can I arrange this without exec or sp_executesql?

I'm using SQL Server 2008.

Thank you.

UPDATE

I've found some links

http://www.eggheadcafe.com/software/aspnet/29397800/dynamically-specify-serve.aspx

http://www.sommarskog.se/dynamic_sql.html

Is using SYNONYM possible solution? If yes, than how?

UPDATE 2

I forgot to mention that all this servers are linked to the server where stored procedure is stored.

UPDATE 3

OPENROWSET or OPENDATASOURCE are not accessible either. I need a solution without building query string concating server name, schema name, db name.

It surely can be using if or case in stored procedure, but if we have 37 variations, then it's not a good solution.

Any other suggestions?

A: 

Does OPENROWSET or OPENDATASOURCE help?

EDIT: If it works, you can change the database at runtime & execute the query using the present connection. I cannot see any other way of executing query the way you want.

What is wrong with running query using string i.e dynamic query?

shahkalpesh
These are linked servers, so I don't have problems with connecting to them. OPENROWSET or OPENDATASOURCE don't solve my problem, I just don't want to put my query in a string type.
hgulyan
@hgulyan But these take a string which you can easily build by concatenation.
Martin Smith
@Martin Smith, I would do that with parameterized sp_executesql, if I have wanted to build my query string.
hgulyan
@shahkalpesh, I have edited my questions. You see, the reason why I don't want exec or sp_executesql is that I don't want generating query string concating, as I said in update 3.
hgulyan
@hgulyan Well it isn't possible then without some massive set of if statements.
Martin Smith
@Martin Smith, than write it as an answer and I'll accept it. I consider that I have to use sp_executesql.
hgulyan
@hgulyan - Leave the question open for a bit incase someone does have an idea of how this can be achieved. I definitely can't think of any way though!
Martin Smith
@Martin Smith, I can't find any other solution either:(p.s. anyway post your answer. I'll wait a while and accept your answer.
hgulyan
@hgulyan Does gbn's answer here help at all or is it not applicable to what you are doing? http://stackoverflow.com/questions/2073544/set-database-name-dynamically-in-sql-server-stored-procedure
Martin Smith
I didn't get how it works. Where should I add my query and what @p1, @p2?
hgulyan
A: 

Nobody wants to answer, so I'll do it myself, just to have accepted answer.

There's isn't any way to do this. You need to use one of specified suggestions, anyway the query must be generating by concatenating.

hgulyan